-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.ts
58 lines (51 loc) · 1.1 KB
/
tree.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
class TreeNode {
public data: any;
public right: TreeNode;
public left: TreeNode;
constructor(data: any, left?: TreeNode, right?: TreeNode) {
this.data = data;
this.left = left;
this.right = right;
}
public show(): TreeNode {
return this.data;
}
}
export class BST {
public root: TreeNode;
constructor(data) {
this.root = new TreeNode(data);
}
public insert(data: any): void {
const n = new TreeNode(data);
if (this.root === undefined) {
this.root = n;
} else {
let current = this.root;
let parent;
while (true) {
parent = current;
if (data < current.data) {
current = current.left;
if (current == null) {
parent.left = n;
break;
}
} else {
current = current.right;
if (current == null) {
parent.right = n;
break;
}
}
}
}
}
public inOrder(node: TreeNode) {
if (node != null) {
this.inOrder(node.left);
console.log(node.show());
this.inOrder(node.right);
}
}
}