-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreeRightSideView.js
More file actions
38 lines (31 loc) · 917 Bytes
/
Copy pathbinaryTreeRightSideView.js
File metadata and controls
38 lines (31 loc) · 917 Bytes
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
const Queue = require('../../../queues/with-object-and-pointers/Queue');
/**
* https://leetcode.com/problems/binary-tree-right-side-view
* Time complexity - O(n)
* Space complexity - O(n)
* @param {TreeNode} root
* @return {number[]}
*/
var binaryTreeRightSideView = function(root) {
const result = []
if (!root)
return result;
var queue = new Queue();
let curr = root;
queue.enqueue(curr);
while (!queue.isEmpty) {
const nextLevelNodes = [];
while (!queue.isEmpty) {
nextLevelNodes.push(queue.dequeue());
}
result.push(nextLevelNodes[nextLevelNodes.length - 1].val);
nextLevelNodes.forEach(node => {
if (node.left)
queue.enqueue(node.left)
if (node.right)
queue.enqueue(node.right)
});
}
return result;
};
module.exports = binaryTreeRightSideView;