forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0102-binary-tree-level-order-traversal.js
56 lines (43 loc) · 1.29 KB
/
0102-binary-tree-level-order-traversal.js
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
53
54
55
56
/**
* https://leetcode.com/problems/binary-tree-level-order-traversal/
* Time O(N) | Space O(W)
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
const isBaseCase = root === null;
if (isBaseCase) return [];
return bfs([ root ]);
};
const bfs = (queue, levels = []) => {
while (queue.length) {
const level = [];
for (let i = (queue.length - 1); 0 <= i; i--) {
const node = queue.shift();
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
level.push(node.val);
}
levels.push(level.slice());
}
return levels;
}
/**
* https://leetcode.com/problems/binary-tree-level-order-traversal/
* Time O(N) | Space O(H)
* @param {TreeNode} root
* @return {number[]}
*/
var levelOrder = function(root, level = 0, levels = []) {
const isBaseCase = root === null;
if (isBaseCase) return levels;
const isLastNode = level === levels.length;
if (isLastNode) levels.push([]);
levels[level].push(root.val);
return dfs(root, level, levels);
}
const dfs = (root, level, levels) => {
if (root.left) levelOrder(root.left, (level + 1), levels);
if (root.right) levelOrder(root.right, (level + 1), levels);
return levels;
}