【剑指Offer】把二叉树打印成多行

题目

从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。

实现

1
2
3
4
5
6
7
8
9
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> results = new ArrayList<>();

if (pRoot != null) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(pRoot);

while (!queue.isEmpty()) {
ArrayList<Integer> result = new ArrayList<>();
int start = 0;
int end = queue.size();

while (start++ < end){
TreeNode node = queue.poll();
result.add(node.val);

if (node.left != null)
queue.offer(node.left);

if (node.right != null)
queue.offer(node.right);
}

results.add(result);
}
}

return results;
}