作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想执行二叉树的层序遍历。因此,对于给定的树,说:
3
/ \
2 1
/ \ \
4 6 10
输出将是:
3 2 1 4 6 10
我知道我可以使用某种队列,但在 C 中递归执行此操作的算法是什么?任何帮助表示赞赏。
最佳答案
该图算法称为广度优先搜索,它使用队列进行层序遍历,这是伪代码
void breadth_first(Node root)
{
Queue q;
q.push(root);
breadth_first_recursive(q)
}
void breadth_first_recursive(Queue q)
{
if q.empty() return;
Node node = q.pop()
print Node
if (n.left) q.push(n.left)
if (n.right) q.push(n.right)
breadth_first_recursive(q)
}
关于c - 二叉树的层序遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15166617/
我是一名优秀的程序员,十分优秀!