-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree-height.ts
103 lines (83 loc) · 2.08 KB
/
tree-height.ts
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
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString: string = '';
let inputLines: string[] = [];
let currentLine: number = 0;
process.stdin.on('data', function (inputStdin: string): void {
inputString += inputStdin;
});
process.stdin.on('end', function (): void {
inputLines = inputString.split('\n');
inputString = '';
main();
});
function readLine(): string {
return inputLines[currentLine++];
}
class NodeTree {
public value: number;
public level: number;
public left?: NodeTree;
public right?: NodeTree;
constructor(value: number, level: number, left?: NodeTree, right?: NodeTree) {
this.value = value;
this.left = left;
this.right = right;
this.level = level;
}
static create(value: number, level: number) {
return new NodeTree(value, level);
}
}
class BinaryTree {
private root: NodeTree | null = null;
public length = 0;
public insert(value: number) {
if (this.root == null) {
this.root = NodeTree.create(value, 0);
} else {
let current = this.root;
while (true) {
if (value > current.value) {
if (!current.right) {
current.right = NodeTree.create(value, current.level + 1);
current = current.right;
break;
} else {
current = current.right;
}
}
if (value < current.value) {
if (!current.left) {
current.left = NodeTree.create(value, current.level + 1);
current = current.left;
break;
} else {
current = current.left;
}
}
}
if (current.level > this.length) {
this.length = current.level;
}
}
}
}
function findHeight(values: number[]) {
const tree = new BinaryTree();
values.forEach((v) => {
tree.insert(v);
});
return tree.length;
}
// expect 3
function main() {
readLine();
const input: number[] = readLine()
.replace(/\s+$/g, '')
.split(' ')
.map((arrTemp) => parseInt(arrTemp, 10));
const len = findHeight(input);
console.log(len);
}