forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
78 lines (67 loc) · 1.86 KB
/
index.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
/**
* Given a Binary Tree, convert it to a Binary Search Tree.
* The conversion must be done in such a way that keeps the original structure of Binary Tree.
* Example 1
Input:
10
/ \
2 7
/ \
8 4
Output:
8
/ \
4 10
/ \
2 7
*/
const Node = require('../../_DataStructures_/Trees/BinaryTree/Node');
// Helper function to store inorder traversal of a binary tree
function storeInorder(root) {
/** left - root - right */
if (root === null) return [];
// First store the left subtree
let arr = [];
const left = storeInorder(root.leftChild);
arr = [...left, ...arr];
// Append root's data
arr = [...arr, root.value];
// Store right subtree
const right = storeInorder(root.rightChild);
arr = [...arr, ...right];
return arr;
}
// Helper function to copy elements from sorted array to make BST while keeping same structure
// Runtime complexity iof this function is O(n) where n is number of nodes, as we are each node of tree one time.
function arrayToBST(arr, root) {
const node = root;
// Base case
if (!node) return null;
const bstNode = new Node();
// First update the left subtree
const leftChild = arrayToBST(arr, node.leftChild);
if (leftChild) {
bstNode.leftChild = leftChild;
}
// update the root's data and remove it from sorted array
// eslint-disable-next-line no-param-reassign
bstNode.value = arr.shift();
// Finally update the right subtree
const rightChild = arrayToBST(arr, node.rightChild);
if (rightChild) {
bstNode.rightChild = rightChild;
}
return bstNode;
}
function binaryTreeToBST(bTree) {
// Tree is empty
if (!bTree.root) return null;
const arr = bTree.preOrder();
arr.sort((a, b) => a - b);
const bst = arrayToBST(arr, bTree.root);
return bst;
}
module.exports = {
binaryTreeToBST,
storeInorder,
};