|
| 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