Skip to content

Commit 2ba8925

Browse files
committed
Implement Binary Tree to Binary Search Tree Conversion - Solution
1 parent 43ed1bc commit 2ba8925

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = class Node {
2+
constructor(value) {
3+
this.value = value;
4+
this.leftChild = null; // will be a node
5+
this.rightChild = null; // will be a node
6+
}
7+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const { binaryTreeToBST, storeInorder } = require('.');
2+
const Node = require('./Node');
3+
4+
describe('Binary tree to binary search tree', () => {
5+
let tree;
6+
7+
describe('Create Binary Tree', () => {
8+
tree = new Node(10);
9+
tree.leftChild = new Node(30);
10+
tree.leftChild.leftChild = new Node(20);
11+
tree.rightChild = new Node(15);
12+
tree.rightChild.rightChild = new Node(5);
13+
});
14+
15+
it('Should converted binary tree to binary search tree', () => {
16+
binaryTreeToBST(tree);
17+
expect(storeInorder(tree)).toEqual([5, 10, 15, 20, 30]);
18+
});
19+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* Given a Binary Tree, convert it to a Binary Search Tree.
3+
* The conversion must be done in such a way that keeps the original structure of Binary Tree.
4+
* Example 1
5+
Input:
6+
10
7+
/ \
8+
2 7
9+
/ \
10+
8 4
11+
Output:
12+
8
13+
/ \
14+
4 10
15+
/ \
16+
2 7
17+
*/
18+
19+
// Helper function to store inorder traversal of a binary tree
20+
function storeInorder(root) {
21+
/** left - root - right */
22+
if (root === null) return [];
23+
24+
// First store the left subtree
25+
let arr = [];
26+
const left = storeInorder(root.leftChild);
27+
arr = [...left, ...arr];
28+
29+
// Append root's data
30+
arr = [...arr, root.value];
31+
32+
// Store right subtree
33+
const right = storeInorder(root.rightChild);
34+
arr = [...arr, ...right];
35+
return arr;
36+
}
37+
38+
// Helper function to copy elements from sorted array to make BST while keeping same structure
39+
function arrayToBST(arr, root) {
40+
const node = root;
41+
// Base case
42+
if (!node) return;
43+
44+
// First update the left subtree
45+
arrayToBST(arr, node.leftChild);
46+
47+
// update the root's data and remove it from sorted array
48+
node.value = arr.shift();
49+
50+
// Finally update the right subtree
51+
arrayToBST(arr, node.rightChild);
52+
}
53+
54+
function binaryTreeToBST(root) {
55+
// Tree is empty
56+
if (!root) return;
57+
const arr = storeInorder(root);
58+
arr.sort((a, b) => a - b);
59+
arrayToBST(arr, root);
60+
}
61+
62+
module.exports = {
63+
binaryTreeToBST,
64+
storeInorder,
65+
};

0 commit comments

Comments
 (0)