-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSearchTree.ts
30 lines (25 loc) · 860 Bytes
/
SearchTree.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
import { TreeNode } from './BinaryTree'
// 二叉搜索树
class SearchTree {
root: TreeNode
constructor(array: number[]) {
for(let i = 0; i < array.length; i++) {
if (i === 0) {
this.root = new TreeNode(array[i])
}
this.add(this.root, array[i])
}
}
public add (root: TreeNode, value: number):void {
if (root.val > value && root.left === undefined) {
root.left = new TreeNode(value)
} else if (root.val < value && root.right === undefined) {
root.right = new TreeNode(value)
} else if (root.val > value && root.left !== undefined) {
this.add(root.left, value)
} else if (root.val < value && root.right !== undefined) {
this.add(root.right, value)
}
}
}
export default SearchTree