这个问题是在我的一次面试中问到的:
假设我们有上面的二叉树,如何生成下面这样的输出结果:
假设我们有上面的二叉树,如何生成下面这样的输出结果:
2 7 5 2 6 9 5 11 4
我回答说,也许我们可以有一个层级计数变量,并通过检查每个节点的层级计数变量按顺序打印所有元素。可能我错了。
有人能给出任何关于如何实现这一点的想法吗?
2 7 5 2 6 9 5 11 4
我回答说,也许我们可以有一个层级计数变量,并通过检查每个节点的层级计数变量按顺序打印所有元素。可能我错了。
有人能给出任何关于如何实现这一点的想法吗?
tree
----
j <-- level 0
/ \
f k <-- level 1
/ \ \
a h z <-- level 2
\
d <-- level 3
人们喜欢从0开始编号。
因此,如果我们想要逐层(通常是从左到右)访问元素,我们会从第0层开始用j,然后转到第1层的f和k,再到第2层的a、h和z,最后到第3层的d。
这种逐层遍历称为广度优先遍历,因为我们在向下深入之前,会先探索给定级别的树的宽度。
levelorder(root)
q = empty queue
q.enqueue(root)
while not q.empty do
node := q.dequeue()
visit(node)
if node.left ≠ null
q.enqueue(node.left)
if node.right ≠ null
q.enqueue(node.right)
BFS:
std::queue<Node const *> q;
q.push(&root);
while (!q.empty()) {
Node const *n = q.front();
q.pop();
std::cout << n->data << std::endl;
if (n->left)
q.push(n->left);
if (n->right)
q.push(n->right);
}
#include <queue>
void print(tree* root)
{
queue<tree*> que;
if (!root)
return;
tree *tmp, *l, *r;
que.push(root);
que.push(NULL);
while( !que.empty() )
{
tmp = que.front();
que.pop();
if(tmp != NULL)
{
cout << tmp=>val; //print value
l = tmp->left;
r = tmp->right;
if(l) que.push(l);
if(r) que.push(r);
}
else
{
if (!que.empty())
que.push(NULL);
}
}
return;
}
我会使用一个集合,例如std::list
,来存储当前打印级别的所有元素:
levels[level].push_back(&node);