-
Notifications
You must be signed in to change notification settings - Fork 15
/
binary-tree-level-order-traversal-ii.java
52 lines (44 loc) · 1.36 KB
/
binary-tree-level-order-traversal-ii.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
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: buttom-up level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrderButtom(TreeNode root) {
// write your code here
// iterative version.
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (root == null) {
return res;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int size = 1;
while (!queue.isEmpty()) {
ArrayList<Integer> tempList = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
tempList.add(cur.val);
if (cur.left != null) {
queue.add(cur.left);
}
if (cur.right != null) {
queue.add(cur.right);
}
}
size = queue.size();
res.add(0, tempList);
}
return res;
}
}