-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeGraph.js
More file actions
601 lines (527 loc) · 13.9 KB
/
TreeGraph.js
File metadata and controls
601 lines (527 loc) · 13.9 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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
const print = console.log;
// * TREES AND GRAPHS CHAPTER
/**
* * Graph Definition
*/
const GraphNode = function(val) {
this.val = val;
this.children = [];
this.left = function() {
return this.children[0];
};
this.right = function() {
return this.children[1];
};
};
GraphNode.prototype.insertVal = function(val) {
this.children.push(new GraphNode(val));
return this.children[this.children.length - 1];
};
GraphNode.prototype.insertNode = function(node) {
this.children.push(node);
return this.children[this.children.length - 1];
};
GraphNode.prototype.remove = function(child = null) {
if (child) this.children[child] = null;
else this.children = [];
};
GraphNode.prototype.setLeft = function(val) {
this.children[0] = new GraphNode(val);
return this.children[0];
};
GraphNode.prototype.setRight = function(val) {
this.children[1] = new GraphNode(val);
return this.children[1];
};
/**
* ! Graph Defintion
*/
/**
* * Tree Traversals
* Assuming first half is on the left and
* rest is on the right for children.length > 2
*/
(function() {
const inOrderTraversal = function(root) {
if (!root) return;
const middle = Math.floor(root.children.length / 2);
// Visit left
for (let i = 0; i < middle; i += 1) {
inOrderTraversal(root.children[i]);
}
// Visit current one
print(root.val);
//Visit right
for (let i = middle; i < root.children.length; i += 1) {
inOrderTraversal(root.children[i]);
}
};
const preOrderTraversal = function(root) {
if (!root) return;
// Visit current one
print(root.val);
const middle = Math.floor(root.children.length / 2);
// Visit left
for (let i = 0; i < middle; i += 1) {
preOrderTraversal(root.children[i]);
}
//Visit right
for (let i = middle; i < root.children.length; i += 1) {
preOrderTraversal(root.children[i]);
}
};
const postOrderTraversal = function(root) {
if (!root) return;
const middle = Math.floor(root.children.length / 2);
// Visit left
for (let i = 0; i < middle; i += 1) {
postOrderTraversal(root.children[i]);
}
//Visit right
for (let i = middle; i < root.children.length; i += 1) {
postOrderTraversal(root.children[i]);
}
// Visit current one
print(root.val);
};
const BFS = function(root) {
if (!root) return;
const queue = [];
queue.push(root);
queue.push(null); // level change
while (queue.length > 0) {
let visiting = queue.shift();
if (visiting === null) {
// New level
print('----');
queue.push(null);
if (queue[0] === null) break;
// You are encountering two consecutive null means
// you visited all the nodes.
else continue;
}
// Visit the current
print(visiting.val);
// push all the child of visiting to queue
queue.push(...visiting.children);
}
};
});
/**
* ! Tree Traversals
*/
/**
* * Binary Heap Definition
*/
(function() {
const BinaryHeap = function() {
this.values = [];
this.size = 0;
};
BinaryHeap.prototype.peek = function() {
if (this.values.length !== 0) return this.values[0];
return null;
};
BinaryHeap.prototype.insert = function(val) {
this.values.push(val);
this.size += 1;
const heapify = function() {
let index = this.values.length;
let parent = Math.floor(index / 2);
while (parent > 0 && this.values[index - 1] < this.values[parent - 1]) {
// Swap index with parent
let temp = this.values[parent - 1];
this.values[parent - 1] = this.values[index - 1];
this.values[index - 1] = temp;
index = parent;
parent = Math.floor(index / 2);
}
};
heapify.apply(this);
};
BinaryHeap.prototype.extractMin = function() {
if (this.values.length === 0) return null;
this.size -= 1;
if (this.values.length === 1) {
let temp = this.values[0];
this.values = [];
return temp;
}
const temp = this.values[0];
this.values[0] = this.values.pop();
const heapify = function() {
let index = 1;
let [left, right] = [index * 2, index * 2 + 1];
let child = left;
if (this.values[right - 1] < this.values[left - 1]) child = right;
index -= 1;
child -= 1;
while (
child < this.values.length &&
this.values[child] < this.values[index]
) {
// Swap index with child
let temp = this.values[index];
this.values[index] = this.values[child];
this.values[child] = temp;
index = child + 1;
[left, right] = [index * 2, index * 2 + 1];
child = left;
if (this.values[right - 1] < this.values[left - 1]) child = right;
index -= 1;
child -= 1;
}
};
heapify.apply(this);
return temp;
};
const heapSort = function(arr) {
const heap = new BinaryHeap();
for (let i = 0; i < arr.length; i++) {
heap.insert(arr[i]);
}
while (heap.peek() !== null) {
print(heap.extractMin());
}
};
});
/**
* ! Binary Heap Definiton
*/
/**
* * Binary Search Tree Definition
* insert(), size, clear(), find(), getHeight()
* getMin(), getMax(), isBinary(), remove()
*/
const BSTNode = function(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
};
(function() {
const BST = function() {
this.root = null;
this.size = 0;
};
BSTNode.prototype.insert = function(val) {
if (this.val > val) {
// Go to left
if (!this.left) this.left = new BSTNode(val);
else this.left.insert(val);
} else {
if (!this.right) this.right = new BSTNode(val);
else this.right.insert(val);
}
};
BSTNode.prototype.find = function(val) {
if (this.val === val) return this;
if (this.val > val && this.left) return this.left.find(val);
else if (this.val < val && this.right) return this.right.find(val);
else return null;
};
BSTNode.prototype.getHeight = function() {
let leftHeight, rightHeight;
if (this.left) leftHeight = this.left.getHeight();
else leftHeight = 0;
if (this.right) rightHeight = this.right.getHeight();
else rightHeight = 0;
let height = Math.max(leftHeight, rightHeight);
return height + 1;
};
BSTNode.prototype.getMax = function() {
if (this.right) return this.right.getMax();
return this.val;
};
BSTNode.prototype.getMin = function() {
if (this.left) return this.left.getMin();
return this.val;
};
// * successor is Question 4.6
BST.prototype.insert = function(val) {
this.size += 1;
if (!this.root) {
this.root = new BSTNode(val);
return;
}
this.root.insert(val);
};
BST.prototype.find = function(val) {
if (!this.root) return false;
return !!this.root.find(val);
};
BST.prototype.getHeight = function() {
if (!this.root) return 0;
return this.root.getHeight();
};
BST.prototype.getMax = function() {
if (!this.root) return null;
return this.root.getMax();
};
BST.prototype.getMin = function() {
if (!this.root) return null;
return this.root.getMin();
};
BST.prototype.clear = function() {
this.root = null;
};
const inOrderTraversal = function(root) {
if (!root) return;
inOrderTraversal(root.left);
print(root.val);
inOrderTraversal(root.right);
};
// TODO: remove()
// * isBinary is Question 4.5
})();
/**
* * Binary Search on sorted Array
*/
(function() {
let sortedArr = [1, 3, 5, 6, 7, 9, 12, 15, 20, 22];
sortedArr.push(...[23, 25, 28, 29, 35, 43, 47, 50, 55]);
const binarySearch = (nums, target) => {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
let m = Math.floor((left + right) / 2); // get middle
if (nums[m] < target) left = m + 1;
else if (nums[m] > target) right = m - 1;
else return m;
}
return null;
};
});
/**
* ! BinarySearch on sorted Array
*/
/**
* * Question 4.2 Minimal Tree
*/
(function() {
const nums = [1, 3, 5, 8, 9, 11, 14, 16, 18, 19, 20];
const root = new BSTNode(nums[Math.floor(nums.length / 2)]);
const createBST = function(root, nums) {
if (nums.length <= 1) return;
let middle = Math.floor(nums.length / 2);
let left = Math.floor(middle / 2);
let right = Math.floor(middle / 2) + Math.ceil(nums.length / 2);
if (left === right) right++;
print(left, right, nums);
root.left = new BSTNode(nums[left]);
if (nums.length !== 2) root.right = new BSTNode(nums[right]);
createBST(root.left, nums.slice(0, middle));
createBST(root.right, nums.slice(middle + 1));
};
createBST(root, nums);
});
/**
* ! Question 4.2
*/
/**
* * Question 4.3 List of Depths
* This can easily be converted to a linkedList
*/
(function() {
const depths = [];
const createDepthList = function(root, depth) {
if (!root) return;
if (depths.length === depth) depths.push([root.val]);
else depths[depth].push(root.val);
createDepthList(root.left(), depth + 1);
createDepthList(root.right(), depth + 1);
};
});
/**
* ! Question 4.3
*/
/**
* * Question 4.4 Check Balanced
*/
(function() {
let res = true;
BSTNode.prototype.checkBalanced = function() {
let leftHeight, rightHeight;
if (this.left) leftHeight = this.left.getHeight();
else leftHeight = 0;
if (this.right) rightHeight = this.right.getHeight();
else rightHeight = 0;
if (Math.abs(leftHeight - rightHeight) > 1) res = false;
let height = Math.max(leftHeight, rightHeight);
return height + 1;
};
});
/**
* ! Question 4.4
*/
/**
* * Question 4.5 Validate BST
* We can store max of left sub-tree and min of right sub-tree
* and check if values hold the BST property for the parent
*/
(function() {
let res = true;
BSTNode.prototype.getMinMax = function() {
// A leaf node
if (!this.left && !this.right) return [this.val, this.val];
let left, right;
let min = this.val,
max = this.val;
// Get the maximum of left side
if (this.left) {
left = this.left.getMinMax();
// max from left can't be greater than this.val
if (this.val < left[1]) {
res = false;
return [null, null];
}
max = left[1];
}
// Get the minimum of right side
if (this.right) {
right = this.right.getMinMax();
// min from right can't be less than this.val
if (this.val > right[0]) {
res = false;
return [null, null];
}
min = right[0];
}
print(this.val, left, right);
return [max, min];
};
});
/**
* ! Question 4.5
*/
/**
* * Question 4.6 Successor
* BSTNode needs to have a parent pointer as well.
*/
(function() {
const BSTParent = function(val, parent = null) {
this.val = val;
this.left = null;
this.right = null;
this.parent = parent;
};
BSTParent.prototype.getMin = BSTNode.prototype.getMin;
BSTParent.prototype.successor = function() {
if (!this.right) return this.getLeftParent();
return this.right.getMin();
};
BSTParent.prototype.getLeftParent = function() {
if (!this.parent) return null;
if (this.parent.left === this) return this.parent.val;
else {
return this.parent.getLeftParent();
}
};
});
/**
* ! Question 4.6
*/
/**
* * Question 4.7 Build Order
* Simple Topological Sort on Dependency Adjacency Matrix in this case..
* projects is an array, dependencies is an array of arrays(size 2)
*/
(function() {
const createHash = function(projects, dependencies) {
// Create adjacency matrix
const depends = {};
for (let i = 0; i < dependencies.length; i += 1) {
let dependent = dependencies[i][1];
let dependency = dependencies[i][0];
if (depends[dependent] === undefined) {
depends[dependent] = {
[dependency]: true
};
} else {
depends[dependent][dependency] = true;
}
}
return depends;
};
const dependencySort = function(projects, dependencies) {
const depends = createHash(projects, dependencies);
let sorted = [];
let nondependent = [];
print(depends);
// Fill nondependent array at the beginning
for (let i = 0; i < projects.length; i += 1) {
if (!depends[projects[i]]) nondependent.push(projects[i]);
}
// Start Topological Sort
while (nondependent.length > 0) {
let node = nondependent.shift();
sorted.push(node);
for (let dependent in depends) {
if (depends[dependent][node]) {
delete depends[dependent][node];
if (Object.keys(depends[dependent]).length === 0) {
nondependent.push(dependent);
delete depends[dependent];
}
}
}
}
return sorted;
};
});
/**
* ! Question 4.7
*/
/**
* * Question 4.8 Lowest Common Ancestor
*/
(function() {
const LCA = function(root, x, y) {
if (!root || root.val == x || root.val == y) return root;
const left = LCA(root.left, x, y);
const right = LCA(root.right, x, y);
if (left === null) return right;
if (right === null) return left;
return root;
};
});
/**
* ! Question 4.8
*/
/**
* * Question 4.9 BST Sequences
*/
(function() {});
/**
* ! Question 4.9
*/
/**
* * Question 4.10 Check Subtree
*/
(function() {
const checkSubtree = function(root1, root2) {
const createUniqSeq = function(root) {
let res = '';
const preOrderTraversal = function(root) {
if (!root) {
res += '.,';
return;
}
res += root.val + ',';
if (!root.left && !root.right) return;
if (!root.left) res += '.,';
else preOrderTraversal(root.left);
if (!root.right) res += '.,';
else preOrderTraversal(root.right);
};
preOrderTraversal(root);
return res;
};
const root1Seq = createUniqSeq(root1);
const root2Seq = createUniqSeq(root2);
if (root1Seq.indexOf(root2Seq) >= 0) return true;
return false;
};
});
/**
* ! Question 4.10
*/