-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree-top-view.js
111 lines (86 loc) · 3.12 KB
/
tree-top-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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
function lessThanOrEqual(nodeA, nodeB) {
return nodeA.data <= nodeB.data;
}
function greaterThan(nodeA, nodeB) {
return nodeA.data > nodeB.data;
}
class Tree {
constructor(rootNode) {
this.root = rootNode;
}
insert(value) {
const node = new Node(value);
const queue = [this.root];
while(queue.length > 0) {
const prospectiveParent = queue.shift();
if (lessThanOrEqual(node, prospectiveParent)) {
if(prospectiveParent.left === null) {
prospectiveParent.left = node;
break;
} else {
queue.push(prospectiveParent.left);
}
} else if (greaterThan(node, prospectiveParent)) {
if(prospectiveParent.right === null) {
prospectiveParent.right = node;
break;
} else {
queue.push(prospectiveParent.right);
}
}
}
}
}
class Node {
constructor(data, left = null, right = null) {
this.data = data;
this.left = left;
this.right = right;
}
}
function processData(input) {
const inputs = input.split("\n");
const args = inputs.filter((input) => !!input);
for (let i = 0; i < args.length; i += 2) {
const numNodes = parseInt(args[i]);
const nodeDatas = (args[i + 1].split(" ")).map((val) => parseInt(val));
const tree = new Tree(new Node(nodeDatas.shift()));
for (const value of nodeDatas) {
tree.insert(value);
}
process.stdout.write(`${topView(tree).map((vertex) => vertex.data)}`.replaceAll(',', ' '));
}
}
function topView(tree) {
if (!tree || !tree.root) return [];
let leftMagnitude = 0;
let rightMagnitude = 0;
const _topView = [{vertex: tree.root, magnitude: 0}];
const queue = [{vertex: tree.root, height: 0}];
while(queue.length > 0) {
const node = queue.shift();
if (node.height < leftMagnitude) {
leftMagnitude = node.height;
_topView.push({ vertex: node.vertex, magnitude: node.height});
} else if (node.height > rightMagnitude) {
rightMagnitude = node.height;
_topView.push({ vertex: node.vertex, magnitude: node.height});
}
if (!!node.vertex.right) {
queue.push({vertex: node.vertex.right, height: node.height + 1});
}
if (!!node.vertex.left) {
queue.push({vertex: node.vertex.left, height: node.height - 1});
}
}
return _topView.sort((a, b) => a.magnitude - b.magnitude).map((val) => val.vertex);
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});