-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBinaryTreeRightSideView.js
53 lines (45 loc) · 1.25 KB
/
BinaryTreeRightSideView.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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
// TC: O(N) SC: O(N)
var rightSideView = function(root) {
const result = [];
const rightView = (root, depth) => {
if(!root) return;
if(result.length === depth) {
result.push(root.val);
}
rightView(root.right, depth + 1);
rightView(root.left, depth + 1);
}
rightView(root, 0);
return result;
};
// Alternate Solution Iteration
function rightSideView(root) {
if (!root) return [];
const result = [];
const queue = [root];
while (queue.length > 0) {
let levelSize = queue.length;
for (let i = 0; i < levelSize; i++) {
let node = queue.shift();
// Add the rightmost node of each level
if (i === levelSize - 1) {
result.push(node.val);
}
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return result;
}