-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.js
118 lines (106 loc) · 2.79 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
106
107
108
109
110
111
112
113
114
115
116
117
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
class BST {
constructor() {
this.root = null;
}
insert(val) {
const newNode = new Node(val)
if(this.root === null) {
this.root = newNode
return this
}
let temp = this.root;
while(true) {
if(temp.val === val) return undefined
if(newNode.val < temp.val ) {
if(temp.left === null ) {
temp.left = newNode
return this // ekta value insert complete and return the this means bst
}
temp = temp.left
} else {
if(temp.right === null) {
temp.right = newNode
return this
}
temp = temp.right
}
}
}
contains(val) {
if(this.root === null) return false
let temp = this.root
while(temp) {
if(val < temp.val) {
temp = temp.left
} else if (val > temp.val) {
temp = temp.right
} else {
return true
}
}
return false;
}
BFS() {
let currentNode = this.root
let queue = [currentNode]
let results= []
while(queue.length){
currentNode = queue.shift()
results.push(currentNode.val)
if(currentNode.left) {
queue.push(currentNode.left)
}
if(currentNode.right) {
queue.push(currentNode.right)
}
}
return results;
}
DFSPreOrder() {
let results = []
function traverse(currentNode){
results.push(currentNode.val)
if(currentNode.left) traverse(currentNode.left)
if(currentNode.right) traverse(currentNode.right)
}
traverse(this.root)
return results;
}
DFSPostOrder() {
let results = []
function traverse(currentNode){
if(currentNode.left) traverse(currentNode.left)
if(currentNode.right) traverse(currentNode.right)
results.push(currentNode.val)
}
traverse(this.root)
return results;
}
DFSInOrder() {
let results = []
function traverse(currentNode){
if(currentNode.left) traverse(currentNode.left)
results.push(currentNode.val)
if(currentNode.right) traverse(currentNode.right)
}
traverse(this.root)
return results;
}
}
const bst = new BST()
bst.insert(10)
bst.insert(11)
bst.insert(12)
bst.insert(13)
bst.insert(14)
bst.insert(9)
bst.insert(8)
bst.insert(7)
console.log(bst.DFSInOrder())