-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathBinary Tree Right Side View.js
59 lines (49 loc) · 1.17 KB
/
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
55
56
57
58
59
/**
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function(root) {
var queue = [],
result = [],
i,
len;
if (!root) {
return result;
}
queue.push(root);
while (queue.length > 0) {
len = queue.length;
for (i = 0; i < len; i++) {
node = queue.shift();
// first one is the right most
if (i === 0) {
result.push(node.val);
}
if (node.right) {
queue.push(node.right);
}
if (node.left) {
queue.push(node.left);
}
}
}
return result;
};