Skip to content

Commit f1feae8

Browse files
Binary Tree Level Order Traversal II
1 parent 6755383 commit f1feae8

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package easy;
2+
3+
import classes.TreeNode;
4+
5+
import java.util.ArrayList;
6+
import java.util.Collections;
7+
import java.util.LinkedList;
8+
import java.util.List;
9+
import java.util.Queue;
10+
11+
/**107. Binary Tree Level Order Traversal II
12+
13+
Total Accepted: 91577
14+
Total Submissions: 258036
15+
Difficulty: Easy
16+
17+
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
18+
19+
For example:
20+
Given binary tree [3,9,20,null,null,15,7],
21+
22+
3
23+
/ \
24+
9 20
25+
/ \
26+
15 7
27+
28+
return its bottom-up level order traversal as:
29+
30+
[
31+
[15,7],
32+
[9,20],
33+
[3]
34+
]
35+
36+
*/
37+
public class BinaryTreeLevelOrderTraversalII {
38+
public List<List<Integer>> levelOrder(TreeNode root) {
39+
List<List<Integer>> result = new ArrayList<List<Integer>>();
40+
if(root == null) return result;
41+
42+
Queue<TreeNode> q = new LinkedList<TreeNode>();
43+
q.offer(root);
44+
while(!q.isEmpty()){
45+
List<Integer> thisLevel = new ArrayList<Integer>();
46+
int qSize = q.size();
47+
for(int i = 0; i < qSize; i++){
48+
TreeNode curr = q.poll();
49+
thisLevel.add(curr.val);
50+
if(curr.left != null) q.offer(curr.left);
51+
if(curr.right != null) q.offer(curr.right);
52+
}
53+
result.add(thisLevel);
54+
}
55+
Collections.reverse(result);//this is the only line that gets added/changed to the previous solution.
56+
return result;
57+
}
58+
}

0 commit comments

Comments
 (0)