-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.js
More file actions
85 lines (77 loc) · 2.29 KB
/
Copy pathbst.js
File metadata and controls
85 lines (77 loc) · 2.29 KB
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
// create a node class
class Node{
constructor(data, left = null, right = null){
this.data = data;
this.left = left;
this.right = right;
}
}
// class to add data to BST
class BST{
constructor(){
this.root = null; //setting the root value to null
}
add(data){ //value to be added is passed into add function
const node = this.root;
// if BST is empty, add the value at the root
if(node == null){
this.root = new Node(data);
return;
} else{
const searchTree = function(node){ // recursive function to compare the value and add to BST.
//checking the left node.
if(data< node.data){
if(node.left === null){
node.left = new Node(data);
return;
} else if (node.left!==null){
return searchTree(node.left);
}
// checking the right node.
} else if(data > node.data){
if(node.right === null){
node.right = new Node(data);
return;
} else if(node.right!==null){
return searchTree(node.right);
}
} else {
return null;
}
};
// Initiating the search function.
return searchTree(node);
}
}
// finding the minimum value in BST
findMin(){
let current = this.root;
while (current.left !==null) {
current = current.left;
}
return current.data;
}
// finding the maximum value in BST
findMax(){
let current = this.root;
while (current.right) {
curretn = current.right;
}
return current.data;
}
// finding a value in BST
find(data){
let current = this.root;
while (current.data !==data) {
if (data< current.data) {
current = curretn.left;
} else {
current = current.right;
}
if (current === null) {
return null;
}
}
return current;
}
}