public class Tree {
TreeNode last;
TreeNode nlast;
public void printTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
last = root;
nlast = root;
while (!queue.isEmpty()) {
TreeNode t = queue.peek();
System.out.print(queue.poll().data + " ");
if (t.left != null) {
queue.add(t.left);
nlast = t.left;
}
if (t.right != null) {
queue.add(t.right);
nlast = t.right;
}
// 如果当前输出结点是最右结点,那么换行
if (last == t) {
System.out.println();
last = nlast;
}
}
}差不多就是用俩指针,一个指向最后节点,另一个一次指向,当便利到的节点等于每行最后一个节点时就换行。。。。。。。。。
转载于:https://blog.51cto.com/fulin0532/1976534
二叉树层次遍历
本文介绍了一种使用队列实现二叉树层次遍历的方法,并通过两个指针记录每层的最后一个节点,以便在遍历过程中正确地换行显示。此算法适用于需要按层次输出二叉树结构的应用场景。
2974

被折叠的 条评论
为什么被折叠?



