-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-insertion.js
99 lines (76 loc) · 2.4 KB
/
binary-tree-insertion.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
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 write(tree) {
if (!tree || !tree.root) return '';
const stack = [tree.root];
while(stack.length > 0) {
const node = stack.pop();
process.stdout.write(`${node.data} `);
if (!!node.right) {
stack.push(node.right);
}
if (!!node.left) {
stack.push(node.left);
}
}
}
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);
}
write(tree);
}
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});