forked from geekxh/hello-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
57 lines (53 loc) · 1.3 KB
/
Solution.java
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author Anonymous
* @since 2019/11/23
*/
/*
* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right =
* null;
*
* public TreeNode(int val) { this.val = val;
*
* }
*
* }
*/
public class Solution {
/**
* 把二叉树打印成多行
*
* @param pRoot 二叉树根节点
* @return 结果list
*/
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
if (pRoot == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(pRoot);
int cnt = 1;
while (cnt > 0) {
int num = cnt;
cnt = 0;
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < num; ++i) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
++cnt;
}
if (node.right != null) {
queue.offer(node.right);
++cnt;
}
res.add(node.val);
}
list.add(res);
}
return list;
}
}