二叉树的层次遍历(按层换行打印)

时间:2021-07-26 11:15:46

概述

二叉树的层次遍历只需使用一个队列即可,但若需要按层来换行打印则稍麻烦一些。

思路

增加两个TreeNode:last和nlast
last:表示当前遍历层最右结点
nlast:表示下一层最右结点
遍历时,每次将nlast指向插入队列元素,最后一个插入结点时即最右结点。插入左右孩子之后,检测last是否为当前输出结点,若是,则表示需要进行换行,并将last指向下一层的nlast。

代码

/*
public class TreeNode {
int data;
TreeNode left;
TreeNode right;

public TreeNode(int data) {
this.data = data;
}
}
*/
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;
}
}
}

public static void main(String[] args) {
// 构建二叉树
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.right.left = new TreeNode(5);
root.right.right = new TreeNode(6);
root.right.left.left = new TreeNode(7);
root.right.left.right = new TreeNode(8);
Tree test = new Tree();
test.printTree(root);
}
}