-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-search-tree.js
69 lines (65 loc) · 1.28 KB
/
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
60
61
62
63
64
65
66
67
68
69
class TreeNode {
constructor(val) {
this.val = val
this.left = null
this.right = null
}
}
class BST {
constructor() {
this.root = null
}
insert(val) {
const temp = new TreeNode(val)
if (!this.root) {
this.root = temp
} else {
let node = this.root
while (true) {
if (node.val > val) {
if (!node.left) {
node.left = temp
return true
}
node = node.left
} else if (node.val < val) {
if (!node.right) {
node.right = temp
return true
}
node = node.right
} else {
throw Error('该节点已存在!')
}
}
}
}
search(val) {
let node = this.root
while (node) {
if (node.val > val) {
node = node.left
} else if (node.val < val) {
node = node.right
} else {
return true
}
}
return false
}
getHeight() {
if (!this.root) return 0
const queue = [this.root]
let ans = 0
while (queue.length) {
ans++
let cnt = queue.length
while (cnt--) {
const temp = queue.shift()
if (temp.left) queue.push(temp.left)
if (temp.right) queue.push(temp.right)
}
}
return ans
}
}