|
| 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 | +const Node = require('../../_DataStructures_/Trees/BinaryTree/Node'); |
| 20 | +// Helper function to store inorder traversal of a binary tree |
| 21 | +function storeInorder(root) { |
| 22 | + /** left - root - right */ |
| 23 | + if (root === null) return []; |
| 24 | + |
| 25 | + // First store the left subtree |
| 26 | + let arr = []; |
| 27 | + const left = storeInorder(root.leftChild); |
| 28 | + arr = [...left, ...arr]; |
| 29 | + |
| 30 | + // Append root's data |
| 31 | + arr = [...arr, root.value]; |
| 32 | + |
| 33 | + // Store right subtree |
| 34 | + const right = storeInorder(root.rightChild); |
| 35 | + arr = [...arr, ...right]; |
| 36 | + return arr; |
| 37 | +} |
| 38 | + |
| 39 | +// Helper function to copy elements from sorted array to make BST while keeping same structure |
| 40 | +// Runtime complexity iof this function is O(n) where n is number of nodes, as we are each node of tree one time. |
| 41 | +function arrayToBST(arr, root) { |
| 42 | + const node = root; |
| 43 | + // Base case |
| 44 | + if (!node) return null; |
| 45 | + |
| 46 | + const bstNode = new Node(); |
| 47 | + // First update the left subtree |
| 48 | + const leftChild = arrayToBST(arr, node.leftChild); |
| 49 | + if (leftChild) { |
| 50 | + bstNode.leftChild = leftChild; |
| 51 | + } |
| 52 | + |
| 53 | + // update the root's data and remove it from sorted array |
| 54 | + // eslint-disable-next-line no-param-reassign |
| 55 | + bstNode.value = arr.shift(); |
| 56 | + |
| 57 | + // Finally update the right subtree |
| 58 | + const rightChild = arrayToBST(arr, node.rightChild); |
| 59 | + if (rightChild) { |
| 60 | + bstNode.rightChild = rightChild; |
| 61 | + } |
| 62 | + |
| 63 | + return bstNode; |
| 64 | +} |
| 65 | + |
| 66 | +function binaryTreeToBST(bTree) { |
| 67 | + // Tree is empty |
| 68 | + if (!bTree.root) return null; |
| 69 | + const arr = bTree.preOrder(); |
| 70 | + arr.sort((a, b) => a - b); |
| 71 | + const bst = arrayToBST(arr, bTree.root); |
| 72 | + return bst; |
| 73 | +} |
| 74 | + |
| 75 | +module.exports = { |
| 76 | + binaryTreeToBST, |
| 77 | + storeInorder, |
| 78 | +}; |
0 commit comments