-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathRightViewOfATree.js
71 lines (66 loc) · 1.95 KB
/
RightViewOfATree.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
60
61
62
63
64
65
66
67
68
69
70
71
/**
* @author Anirudh Sharma
*
* Given a Binary Tree, print Right view of it.
* Left view of a Binary Tree is set of nodes visible when tree is visited from right side.
*/
const rightView = (root) => {
// Array to store the result
const result = [];
// Special case
if (root === null) {
return result;
}
// Queue to store the nodes of the tree
const nodes = [];
// Add root node to the stack
nodes.push(root);
// Loop until the queue is empty
while (nodes.length > 0) {
// Get the size of the queue
let size = nodes.length;
// Loop until the size
for (let i = 0; i < size; i++) {
// Get the current node
let current = nodes.shift();
// If it is the last node at the current level,
// add it to the result
if (i === size - 1) {
result.push(current.data);
}
// Move to the left child if exists
if (current.left !== null) {
nodes.push(current.left);
}
// Move to the right child if exists
if (current.right !== null) {
nodes.push(current.right);
}
}
}
return result;
};
function Node(data, left, right) {
this.data = (data === undefined ? 0 : data);
this.left = (left === undefined ? null : left);
this.right = (right === undefined ? null : right);
}
const main = () => {
let root = new Node(1);
root.left = new Node(3);
root.right = new Node(2);
console.log(rightView(root));
root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(60);
console.log(rightView(root));
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
console.log(rightView(root));
};
main();