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