我有一个非二叉树结构来构建这样的表单节点:
struct Node
{
Node* pa_;
std::vector<Node*> children_;
std::vector<Node*> GetLeaves()
};
通过树叶,我了解没有孩子的树节点。提供树叶集合的方法如下所示:
std::vector<Node*> Node::GetLeaves()
{
std::vector<Node*> ret;
if(!children_.size())
{
ret.push_back(this);
}
else
{
for (auto child : children_)
{
auto child_leaves = child->GetLeaves()
ret.insert( ret.end(),
child_leaves.begin(),
child_leaves.end() );
}
}
return std::move(ret);
}
不要说整棵树可以有数百片叶子。
将向量用作叶子的容器,意味着在插入返回的集合时会发生大量内存重新分配。
问题是:使用std :: list而不是std :: vector不是更好的选择吗?
提前
答案 0 :(得分:0)
避免递归将消除某些复制并允许您仅构建一个列表:
std::vector<Node*> Node::GetLeaves()
{
if (children_.empty())
{
return std::vector<Node*>(this, 1);
}
std::vector<Node*> ret;
std::stack<Node*> nodes;
nodes.push(this);
while (!nodes.empty())
{
Node* parent = nodes.top();
nodes.pop();
for (auto node : parent->children_)
{
if (node->children_.empty())
{
ret.push_back(node);
}
else
{
nodes.push(node);
}
}
}
return ret;
}
如果要更改遍历顺序,可以将stack
更改为queue
。