题目
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印一行。解题思路
用一个队列来保存将要打印的结点。为了把二叉树的每一行单独打印到一行里,我们需要两个变量:一个变量表示在当前的层中还没有打印的结点数,另一个变量表示下一次结点的数目。
public static ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
if(pRoot == null) return list;
queue.add(pRoot);
int now = 1, next = 0;
while(!queue.isEmpty()) {
TreeNode t = queue.remove();
now--;
temp.add(t.val);
if(t.left != null) {
queue.add(t.left);
next++;
}
if(t.right != null) {
queue.add(t.right);
next++;
}
if(now == 0) {
list.add(new ArrayList<Integer>(temp));
temp.clear();
now = next;
next = 0;
}
}
return list;
}
本文介绍了一种按层打印二叉树的方法,利用队列实现对二叉树的层次遍历,每层节点按从左到右顺序输出。通过记录当前层剩余未打印节点数及下一层节点数,确保每一层输出在单独的一行。
1万+

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



