Given a Binary Search Tree which is also a Complete Binary Tree. The problem is to convert a given BST into a Special Max Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied to all the nodes in the so-converted Max Heap.
Explanation: The given BST has been transformed into a Max Heap. All the nodes in the Max Heap satisfy the given condition, that is, values in the left subtree of a node should be less than the values in the right a subtree of the node.
Using Inorder + Postorder Traversal – O(n) Time and O(n) Space
The idea is to first store the BST elements in sorted order using inorder traversal. Since inorder traversal of a BST always produces sorted values, these values can later be reassigned to the tree in postorder fashion. Assigning values during postorder traversal ensures that every parent gets a larger value than its children, thereby converting the BST into a Max Heap while preserving the tree structure.
Perform inorder traversal of BST and store node values in a sorted array
Traverse the tree in postorder manner (left → right → root)
Replace node values sequentially using the sorted array
After reassignment, the tree satisfies Max Heap properties