-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0199_binaryTreeRightSideView.js
42 lines (35 loc) · 1.12 KB
/
0199_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
/**
* @typedef {Object} TreeNode
* @description 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 Root of the binary tree.
* @return {number[]} List of nodes for right side of tree, ordered top to bottom.
* @summary Binary Tree Right Side View {@link https://leetcode.com/problems/binary-tree-right-side-view/}
* @description Given a binary tree, return right side of it, ordered.
* Space O(n) - up to diameter of tree (n/2) in queue at once.
* Time O(n) - traverse each tree element.
*/
const rightSideView = root => {
let current = [];
let next = [root];
const answer = [];
let node = null;
while (next.length) {
current = next;
next = [];
while (current.length) {
node = current.shift();
if (!node) continue;
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
if (!current.length && node) answer.push(node.val);
}
return answer;
};