Binary Tree Right Side View LeetCode solution in JavaScript

1
var rightSideView = function (root) {
2
if (!root) return [];
3
let ans = [];
4
let queue = [root];
5

6
while (queue.length > 0) {
7
let queueLength = queue.length;
8

9
// As we are giving priority to right node,
10
// first node will always be the one that we want in output
11
ans.push(queue[0].val);
12

13
for (let i = 0; i < queueLength; i++) {
14
// Ignore TC of queue.shift (assuming we have queue implementation with O(1) TC)
15
let current = queue.shift();
16

17
// Always give priority to right node
18
if (current.right) queue.push(current.right);
19
if (current.left) queue.push(current.left);
20
}
21
}
22
return ans;
23
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0