-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTS.ts
66 lines (62 loc) · 1.44 KB
/
TS.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
class Node1 {
left: Node1 | null = null;
right: Node1 | null = null;
constructor(public value: number) {}
}
class Tree {
root: Node1 = null;
insert(value: number) {
let node = new Node1(value);
let current = this.root;
if (!this.root) {
this.root = new Node1(value);
return true;
}
while (current !== null) {
if (value < current.value) {
if (current.left === null) {
current.left = node;
break;
} else {
current = current.left;
}
} else {
if (current.right === null) {
current.right = node;
break;
} else {
current = current.right;
}
}
}
return true;
}
search(value: number) {
let current = this.root;
while (current !== null) {
console.log(current.value);
if (value === current.value) {
console.log("get!");
return true;
}
current = value > current.value ? current.right : current.left;
}
console.log("cannot find!");
return false;
}
preOrderTraverse(node: Node1) {
if (node) {
console.log(node.value);
this.preOrderTraverse(node.left);
this.preOrderTraverse(node.right);
}
}
}
// test code
let tree = new Tree();
let dataList = [7, 8, 10, 9, 3, 12, 11, 4, 5, 1, 3];
console.log(Array.isArray(dataList));
dataList.forEach(function(data) {
tree.insert(data);
});
tree.preOrderTraverse(tree.root);