-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-22-binary-search-tree.js
59 lines (47 loc) · 1.32 KB
/
day-22-binary-search-tree.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
// Start of function Node
function Node(data) {
this.data = data;
this.left = null;
this.right = null;
} // End of function Node
// Start of function BinarySearchTree
function BinarySearchTree() {
this.insert = function(root, data) {
if (root === null) {
this.root = new Node(data);
return this.root;
}
if (data <= root.data) {
if (root.left) {
this.insert(root.left, data);
} else {
root.left = new Node(data);
}
} else if (root.right) {
this.insert(root.right, data);
} else {
root.right = new Node(data);
}
return this.root;
};
// Start of function getHeight
this.getHeight = function(root) {
// Add your code here
return 1 + Math.max(root.left !== null ? this.getHeight(root.left) : -1, root.right !== null ? this.getHeight(root.right) : -1);
}; // End of function getHeight
} // End of function BinarySearchTree
process.stdin.resume();
process.stdin.setEncoding('ascii');
let _input = '';
process.stdin.on('data', (data) => {
_input = _input + data;
});
process.stdin.on('end', () => {
let tree = new BinarySearchTree();
let root = null;
let values = _input.split('\n').map(Number);
for (let i = 1; i < values.length; i++) {
root = tree.insert(root, values[i]);
}
console.log(tree.getHeight(root));
});