forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 14
/
199 Binary Tree Right Side View.js
53 lines (43 loc) · 1018 Bytes
/
199 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
// 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 result = [];
if(root === null) {
return result;
}
queue = [];
queue.push(root);
while(queue.length > 0) {
var len = queue.length;
for(var i = 0; i < len; i++) {
var node = queue.shift();
if(node.left) {
queue.push(node.left);
}
if(node.right) {
queue.push(node.right);
}
if(i === len - 1) {
result.push(node.val);
}
}
}
return result;
};