Skip to content

Commit 1d448aa

Browse files
committed
Binary Tree Level Order Traversal II
1 parent d0dd09f commit 1d448aa

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*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).
2+
3+
For example:
4+
Given binary tree [3,9,20,null,null,15,7],
5+
3
6+
/ \
7+
9 20
8+
/ \
9+
15 7
10+
return its bottom-up level order traversal as:
11+
[
12+
[15,7],
13+
[9,20],
14+
[3]
15+
]*/
16+
17+
/**
18+
* Definition for a binary tree node.
19+
* function TreeNode(val) {
20+
* this.val = val;
21+
* this.left = this.right = null;
22+
* }
23+
*/
24+
/**
25+
* @param {TreeNode} root
26+
* @return {number[][]}
27+
*/
28+
var levelOrderBottom = function(root) {
29+
ans = []
30+
h = 0
31+
lobHelper(root,ans,h)
32+
return ans.reverse()
33+
};
34+
35+
var lobHelper = function(node,ans,h){
36+
if(node != null){
37+
if(ans.length == h){
38+
ans[h] = []
39+
}
40+
ans[h].push(node.val)
41+
if(node.left != null){
42+
lobHelper(node.left,ans,h+1)
43+
}
44+
if(node.right != null){
45+
lobHelper(node.right,ans,h+1)
46+
}
47+
}
48+
};

0 commit comments

Comments
 (0)