Skip to content

Commit 67715f0

Browse files
committed
convert BST to min heap
1 parent 678def9 commit 67715f0

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'use strict';
2+
class Node {
3+
constructor(data) {
4+
this.data = data;
5+
this.leftNode = this.rightNode = null;
6+
}
7+
}
8+
9+
function insertionOfk(root, k) {
10+
if (root == null) return new Node(k);
11+
if (root.data > k)
12+
root.leftNode = insertionOfk(root.leftNode, k);
13+
else if (root.data < k)
14+
root.rightNode = insertionOfk(root.rightNode, k);
15+
return root;
16+
}
17+
18+
function inOrder(root, inOrderArr) {
19+
if (root == null) return;
20+
inOrder(root.leftNode, inOrderArr);
21+
inOrderArr.push(root.data);
22+
inOrder(root.rightNode, inOrderArr);
23+
}
24+
25+
function convertToMinHeap(root, inOrderArr) {
26+
if (root == null) return;
27+
root.data = inOrderArr.shift();
28+
convertToMinHeap(root.leftNode, inOrderArr);
29+
convertToMinHeap(root.rightNode, inOrderArr);
30+
}
31+
32+
function preOrderDisplay(root, preOrderArr) {
33+
if (root == null) return;
34+
preOrderArr.push(root.data);
35+
preOrderDisplay(root.leftNode, preOrderArr);
36+
preOrderDisplay(root.rightNode, preOrderArr);
37+
}
38+
39+
let tree = null;
40+
tree = insertionOfk(tree, 4);
41+
tree = insertionOfk(tree, 2);
42+
tree = insertionOfk(tree, 3);
43+
tree = insertionOfk(tree, 1);
44+
tree = insertionOfk(tree, 6);
45+
tree = insertionOfk(tree, 5);
46+
tree = insertionOfk(tree, 7);
47+
48+
// BST
49+
// 4
50+
// / \
51+
// 2 6
52+
// / \ / \
53+
// 1 3 5 7
54+
let preOrderArr = [];
55+
preOrderDisplay(tree, preOrderArr);
56+
console.log('BST Preorder Display - ', preOrderArr.join(', '));
57+
58+
let inOrderArr = [];
59+
inOrder(tree, inOrderArr);
60+
BSTToMinHeap(tree, inOrderArr);
61+
62+
preOrderArr = [];
63+
preOrderDisplay(tree, preOrderArr);
64+
console.log('Min Heap Preorder Display -', preOrderArr.join(', '));

0 commit comments

Comments
 (0)