-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst.js
105 lines (88 loc) · 2.52 KB
/
bst.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
// Binary tree
class Node {
constructor(value = null) {
this.value = value
this.childL = null
this.childR = null
}
}
export default class BST {
constructor() {
this.root = null
}
insert(value) {
if (!this.root) {
this.root = new Node (value)
console.log(`Insert: created root: ${value}`)
return this.root
}
const parent = this.search(this.root, value)
if (parent.value === value) {
console.log(`Insert: tree already contains ${value}. Skipping`)
return parent
}
if (value < parent.value) {
parent.childL = new Node(value)
console.log(`Insert: ${value} is now left child of ${parent.value}`)
return parent.childL
} else {
parent.childR = new Node(value)
console.log(`Insert: ${value} is now right child of ${parent.value}`)
return parent.childR
}
}
// depth first search. return node with matching value. If no matching value, return closest parent, beneath which we would insert value.
search(node = this.root, value) {
if (!node) {
return null
}
if (node.value === value) {
return node
}
if (value < node.value)
return node.childL? this.search (node.childL, value) : node
else
return node.childR? this.search (node.childR, value) : node
}
isEmpty() {
return this.root === null
}
visit(node) {
if (!node)
return
console.log (`${node.value} `)
}
// parent before children
preorderTraverse(node = this.root) {
if (!node) {
return null
}
this.visit (node)
if (node.childL)
this.preorderTraverse(node.childL)
if (node.childR)
this.preorderTraverse(node.childR)
}
// left, parent, right
inorderTraverse(node = this.root) {
if (!node) {
return null
}
if (node.childL)
this.inorderTraverse(node.childL)
this.visit (node)
if (node.childR)
this.inorderTraverse(node.childR)
}
// children before parent
postorderTraverse(node = this.root) {
if (!node) {
return null
}
if (node.childL)
this.postorderTraverse(node.childL)
if (node.childR)
this.postorderTraverse(node.childR)
this.visit (node)
}
}