-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpg116.js
152 lines (125 loc) · 2.34 KB
/
pg116.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
//chapter 11 - binary search trees
const{BST} = require('./BST.js')
const{leaf} = require('./BST.js')
BST.prototype.add = function(val){
var newLeaf = new leaf(val)
if(!this.root){
this.root = newLeaf;
return this;
}
var runner = this.root;
while(runner){
if(val>runner.val){
if(!runner.right){
runner.right = newLeaf;
return;
}
runner = runner.right;
break;
}
else if(val<runner.val){
if(!runner.left){
runner.left = newLeaf;
return;
}
runner = runner.left
}
else{
break;
};
};
};
BST.prototype.contains = function(compare){
if(!this.root){
return false;
}
var runner = this.root;
while(runner){
if(runner.val == compare){
return true;
}
else if(compare > runner.val){
if(runner.right){
runner = runner.right;
continue;
};
return false;
}
else{
if(runner.left){
runner = runner.left;
continue;
};
return false;
}
};
};
BST.prototype.findMin = function(){
if(!this.root){
return false;
}
var rFindMin = function(currentLeaf){
if(currentLeaf.left){
return rFindMin(currentLeaf.left)
}
return currentLeaf.val
}
return rFindMin(this.root);
};
BST.prototype.findMax = function(){
//not checking for root existance...
var rFindMax = function(currentLeaf){
if(currentLeaf.right){
return rFindMax(currentLeaf.right)
}
return currentLeaf.val
}
return rFindMax(this.root)
}
BST.prototype.traverse = function(){
var rTraverse = function(node){
if(node){
if(node.left != null){
rTraverse(node.left);
}
if(node.right != null){
rTraverse(node.right)
}
console.log("this node is...", node.val)
}
}
rTraverse(this.root);
}
BST.prototype.size = function(){
var counter = 1
var addLeaf = function(currentLeaf){
if(currentLeaf.right){
counter++;
addLeaf(currentLeaf.right)
}
if(currentLeaf.left){
counter++
addLeaf(currentLeaf.left)
}
}
addLeaf(this.root);
return counter;
}
BST.prototype.rGetHeight = function(node){
if(!node){
return 0;
}
var left = this.rGetHeight(node.left);
var right = this.rGetHeight(node.right);
return Math.max(left, right) + 1;
}
BST.prototype.getHeight = function(){
return this.rGetHeight(this.root);
}
var newBST = new BST();
newBST.add(10);
console.log(newBST)
newBST.add(15);
newBST.add(5);
console.log(newBST)
console.log(newBST.getHeight())