-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunbalanced-bst.js
435 lines (359 loc) · 11.8 KB
/
unbalanced-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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
var TRAVERSAL = {
PREORDER: 1,
INORDER: 2,
POSTORDER: 3,
};
/***************************************
NODE OBJECT WE USE TO CREATE OUR TREE
****************************************/
function treeNode(left, newData, right) {
// this = {}
if (new.target === undefined) {
console.log('You didnt use new. Giving you a new treeNode');
return new treeNode(null, data, null);
}
// assign properties to self
this.left = left || null;
this.data = newData;
this.right = right || null;
this.display = function() {
console.log(": " +this.data);
};
this.delete = function() {
this.left = null;
this.right = null;
this.data = null;
}
// return this
}
/***************************************
UnBalancedBST
- insert into tree
- remove from tree
- print (inorder, preorder, postorder)
- create balanced tree
- check for balanceness
- search for node in tree
- show how many steps it took for the search
****************************************/
function UnBalancedBST() {
var head = null;
var numOfStepsForSearch = 0;
this.displayNumOfStepsForSearch = function() {
return numOfStepsForSearch;
}
this.getRoot = function() {
return head;
}
/***************************************
SEARCHING IN TREE
****************************************/
// PRIVATE
// O(n)
function traverseSearch(number, node) {
if (node == null) return null;
numOfStepsForSearch++;
if (number > node.data) {
return traverseSearch(number, node.right);
} else if (number < node.data ){
return traverseSearch(number, node.left);
} else if (number == node.data) {
return node;
}
}
// PUBLIC
// returns you the node if found
// null otherwise
this.search = function(numberToFind) {
numOfStepsForSearch = 0;
if (head) {
return traverseSearch(numberToFind, head);
}
}
/***************************************
INSERTING INTO THE TREE
****************************************/
// PRIVATE
function traverseInsertion(numberToInsert, node) {
if (node == null) { return new treeNode(null, numberToInsert, null); }
if (numberToInsert > node.data) {
node.right = traverseInsertion(numberToInsert, node.right);
return node;
} else {
node.left = traverseInsertion(numberToInsert, node.left);
return node;
}
}
// PUBLIC
this.insert = function(number) {
if (head == null) {
head = new treeNode(null, number, null);
} else {
if (number > head.data) { head.right = traverseInsertion(number, head.right); }
else { head.left = traverseInsertion(number, head.left); }
}
};
/***************************************
PRINTING THE TREE
****************************************/
// PRIVATE
function inOrderPrint(node) {
if (node == null) return;
inOrderPrint(node.left);
if (head == node) {
console.log("=============== HEAD ==================");
}
node.display();
if (head == node) {
console.log("=============================================")
}
inOrderPrint(node.right);
}
// PRIVATE
function preOrderPrint(node) {
if (node == null) return;
node.display();
preOrderPrint(node.left);
preOrderPrint(node.right);
}
// PRIVATE
function postOrderPrint(node) {
if (node == null) return;
postOrderPrint(node.left);
postOrderPrint(node.right);
node.display();
}
// PUBLIC
this.print = function(traversalType) {
console.log(" printing tree ");
if (head) {
console.log("Head is " + head.data + "..!");
switch (traversalType) {
case TRAVERSAL.INORDER: inOrderPrint(head);
break;
case TRAVERSAL.PREORDER: preOrderPrint(head);
break;
case TRAVERSAL.POSTORDER: postOrderPrint(head);
default:
}
} else {
console.log("Tree is currently empty.")
}
};
/***************************************
CREATING A BALANCED TREE
****************************************/
// PRIVATE
function inOrderToArray(node, array) {
if (node == null) return;
inOrderToArray(node.left, array);
array.push(node.data);
inOrderToArray(node.right, array);
}
// PUBLIC
// Convert an inordered tree to a sorted array
this.flattenInOrderToSortedArray = function() {
var sortedArray = [];
if (head) {
inOrderToArray(head, sortedArray);
}
return sortedArray;
}
// PRIVATE
// Build a balanced tree from the sorted array
// where the left/right node takes on the mid of
// the left/right sides of the array.
function buildBalancedTree(array) {
if (array.length == 0) { return null; }
var mid = Math.floor((array.length)/2);
var n = new treeNode(null, array[mid], null);
var arrayOnLeft = array.slice(0, mid);
n.left = buildBalancedTree(arrayOnLeft);
var arrayOnRight= array.slice(mid+1);
n.right = buildBalancedTree(arrayOnRight);
return n;
}
// PUBLIC
// convert the incoming array into a balanced tree
this.sortedArrayToBalancedTree = function(array) {
if (head) {
return buildBalancedTree(array);
}
return null;
};
/***************************************
BALANCENESS OF A TREE
***************************************/
// PRIVATE
// will send 'false' to callback for any unbalanceness
function countBalance(node, balancedCallBack) {
if (node == null) { return -1; }
var leftCount = 1 + countBalance(node.left, balancedCallBack);
var rightCount = 1 + countBalance(node.right, balancedCallBack);
if (Math.abs(leftCount-rightCount) > 1) {
balancedCallBack(false, node);
}
return (leftCount >= rightCount) ? leftCount : rightCount;
}
// PUBLIC
// Checks to see if an unbalanceness exist in the tree
this.checkForBalanceness = function(balancedTree) {
var balancenessExist = true;
countBalance(balancedTree, function(balanced = true, node) {
if (balanced == false) {
balancenessExist = balanced
}
});
console.log("Does Balancess Exist? : " + balancenessExist);
}
/***************************************
REMOVING FROM THE TREE
***************************************/
// PUBLIC
// if we're removing the root, we take care of it here.
// if we remove from anywhere else, we use traverseRemove
this.remove = function(number) {
console.log("Let's remove: " + number);
if (head) {
if (head.data == number && rightChildOnly(head)) {
var temp = head; head = head.right; temp.delete();
return head;
}
else if (head.data == number && leftChildOnly(head)) {
var temp = head; head = head.left; temp.delete();
return head;
}
else if (head.data == number && noChildren(head)) {
head.delete(); head = null;
return head;
}
return this.traverseRemove(number, head);
} else {
console.log("Empty tree. Nothing to remove");
}
};
//PRIVATE
// Finds the minimum of sub-tree and delete it
function deleteMinimum(node, removeCallBack) {
if (noChildren(node)) {
removeCallBack(node);
return null;
}
if (rightChildOnly(node)) {
removeCallBack(node);
return node.right;
}
if (node.left) {
node.left = deleteMinimum(node.left, removeCallBack);
return node;
}
}
//PRIVATE UTILITY FOR CHECKING NODE'S CHILDREN EXISTENCE
function noChildren(node) {
return (node.left == null && node.right == null);
}
function leftChildOnly(node) {
return (node.left != null && node.right == null);
}
function rightChildOnly(node) {
return (node.left == null && node.right != null);
}
function bothChildExist(node) {
return (node.left != null && node.right != null);
}
// PUBLIC
//
this.traverseRemove = function (number, node) {
if (node == null) {
console.log("You're at leaf end, null. Number " + number + " not found. :P )");
return null;
}
if (number > node.data) {
node.right = this.traverseRemove(number, node.right);
return node;
} else if (number < node.data) {
node.left = this.traverseRemove(number, node.left);
return node;
} else if (number == node.data) {
if (noChildren(node)) {
node.delete(); return null;
}
if (leftChildOnly(node)) {
var leftNodeRef = node.left; node.delete(); return leftNodeRef;
}
if (rightChildOnly(node)) {
var rightNodeRef = node.right; node.delete(); return rightNodeRef;
}
if (bothChildExist(node)) {
var nodeToDelete;
node.right = deleteMinimum(node.right, function(toRemove){
node.data = toRemove.data;
nodeToDelete = toRemove;
});
nodeToDelete.delete();
return node;
}
} // FOUND
} // traverseRemove function
//The height of a binary tree is the number of edges between the tree's root
// and its furthest leaf node. This means that a tree containing a single node has a height of 0.
// inner function, cannot access parent scope's this
function getHeight(node) {
if (node == null) return 0;
if (node.left == null && node.right == null) { return 0; }
var leftCount, rightCount = 0; // at every node, we begin with 0
// if the left exist, we count the edge
if (node.left) { leftCount = getHeight(node.left) + 1; }
// right right exist, we count the edge
if (node.right) { rightCount = getHeight(node.right) + 1; }
return (leftCount > rightCount) ? leftCount : rightCount;
}
// GET HEIGHT OF Tree
this.height = function() {
if (head) {
return getHeight(head);
}
}
}
UnBalancedBST.CreateObject = function() {
return new UnBalancedBST();
}
var myBST = UnBalancedBST.CreateObject();
myBST.insert(50);
myBST.insert(40);
myBST.insert(30);
myBST.insert(45);
myBST.insert(90);
myBST.insert(82);
myBST.insert(96);
myBST.insert(98);
myBST.insert(99);
myBST.print(TRAVERSAL.INORDER);
console.log("height of tree is:");
console.log(myBST.height());
/*
console.log("------ Change unbalanced tree into a balanced tree -------");
var array = myBST.flattenInOrderToSortedArray();
var balancedTree = myBST.sortedArrayToBalancedTree(array);
myBST.checkForBalanceness(balancedTree);
console.log("===== Test the Balanceness of the Original Tree");
myBST.checkForBalanceness(myBST.getRoot());
myBST.remove(90);
myBST.print(TRAVERSAL.INORDER);
myBST.remove(40);
myBST.print(TRAVERSAL.INORDER);
myBST.remove(50);
myBST.print(TRAVERSAL.INORDER);
myBST.remove(45);
myBST.print(TRAVERSAL.INORDER);
myBST.remove(30);
myBST.print(TRAVERSAL.INORDER);
myBST.remove(82);
myBST.print(TRAVERSAL.INORDER);
myBST.remove(98);
myBST.print(TRAVERSAL.INORDER);
myBST.remove(99);
myBST.print(TRAVERSAL.INORDER);
myBST.remove(96);
myBST.print(TRAVERSAL.INORDER);
*/