-
Notifications
You must be signed in to change notification settings - Fork 150
/
LevelPrintTree61.java
50 lines (46 loc) · 1.26 KB
/
LevelPrintTree61.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
package com.so;
import java.util.*;
import com.so.Common.TreeNode;
/**
* 第61题
* 把二叉树打印成多行,从上到下按层打印二叉树,同一层结点从左至右输出。
*
* @author qgl
* @date 2017/08/30
*/
public class LevelPrintTree61 {
/**
* 从左至右打印每行二叉树
* @param pRoot
* @return
*/
public static ArrayList<ArrayList<Integer>> printTreeNodeByLeftToRight(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if (pRoot == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
ArrayList<Integer> tmp = new ArrayList<>();
int start = 0;
int end = 1;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
tmp.add(node.val);
start++;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
if (start == end) {
start = 0;
end = queue.size();
res.add(new ArrayList<>(tmp));
tmp.clear();
}
}
return res;
}
}