-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy path107-binary-tree-level-order-traversal-ii.js
More file actions
45 lines (42 loc) · 1.09 KB
/
107-binary-tree-level-order-traversal-ii.js
File metadata and controls
45 lines (42 loc) · 1.09 KB
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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
const levelOrderBottom = function(root) {
const levels = []
postOrderTraversal(root)
return levels.reverse()
function postOrderTraversal(node, level = 0) {
if (node) {
if (!levels[level]) levels.push([])
postOrderTraversal(node.left, level + 1)
postOrderTraversal(node.right, level + 1)
levels[level].push(node.val)
}
}
}
// another
const levelOrderBottom = function(root) {
if (!root) return []
const currentLevelNodes = [root]
const result = []
while (currentLevelNodes.length > 0) {
const count = currentLevelNodes.length
const currentLevelValues = []
for (let i = 0; i < count; i++) {
const node = currentLevelNodes.shift()
currentLevelValues.push(node.val)
if (node.left) currentLevelNodes.push(node.left)
if (node.right) currentLevelNodes.push(node.right)
}
result.unshift(currentLevelValues)
}
return result
}