-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-search-tree.js
129 lines (102 loc) · 3.04 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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class BinarySearchTree {
constructor(value) {
this.value = value
this.left = null
this.right = null
}
traversePreOrder() {
// shows keys in order, by walking:
// - root
// - left subtree nodes
// - right subtree nodee (do this recursively)
console.log(this.value)
if(this.left) {
this.left.traversePreOrder()
}
if(this.right) {
this.right.traversePreOrder()
}
}
traverseInOrder() {
// shows keys in order, by walking:
// - nodes in left subtree
// - root
// - nodes in right subtree
if(this.left) {
this.left.traverseInOrder()
}
console.log(this.value)
if(this.right) {
this.right.traverseInOrder()
}
}
traversePostOrder() {
// shows keys in order, by walking:
// - nodes in left subtree
// - nodes in right subtree
// - root
if(this.left) {
this.left.traversePostOrder()
}
if(this.right) {
this.right.traversePostOrder()
}
console.log(this.value)
}
insert(value) {
const newNode = new BinarySearchTree(value)
// insert nodes to left subtree
if(newNode.value < this.value && this.left === null) {
this.left = newNode
} else if(newNode.value < this.value && this.left) {
this.left.insert(newNode.value)
}
// insert nodes to right subtree
if(newNode.value > this.value && this.right === null) {
this.right = newNode
} else if(newNode.value > this.value && this.right) {
this.right.insert(newNode.value)
}
}
contains(value) {
if(value === this.value) {
return true
}
const isValueInLeft = this.left &&
this.left.contains(value) ? true : false
const isValueInRight = this.right &&
this.right.contains(value) ? true : false
return isValueInLeft || isValueInRight
}
bstHeight() {
let left = this.left ? this.left.bstHeight() : -1
let right = this.right ? this.right.bstHeight() : -1
if(left > right) {
return left += 1
} else {
return right += 1
}
}
}
// const myBST = new BinarySearchTree(10)
// myBST.insert(8)
// myBST.insert(13)
// myBST.insert(3)
// myBST.insert(1)
// myBST.insert(3)
// myBST.insert(5)
// myBST.insert(0)
// myBST.insert(5)
// myBST.insert(11)
// myBST.insert(3)
// myBST.insert(4)
// myBST.insert(11)
// myBST.insert(9)
// myBST.insert(2)
// myBST.insert(8)
// myBST.insert(3)
// myBST.insert(1)
// console.log(myBST)
// console.log("traversePreOrder", myBST.traversePreOrder())
// console.log("traverseInOrder", myBST.traverseInOrder())
// console.log("traversePostOrder", myBST.traversePostOrder())