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 on all the nodes in the so converted Max Heap.
Input : 4 / \ 2 6 / \ / \ 1 3 5 7 Output : 7 / \ 3 6 / \ / \ 1 2 4 5 The given BST has been transformed into a Max Heap. All the nodes in the Max Heap satisfies the given condition, that is, values in the left subtree of a node should be less than the values in the right subtree of the node.
1. Create an array arr of size n, where n is the number of nodes in the given BST.
2. Perform the inorder traversal of the BST and copy the node values in the arr in sorted
3. Now perform the postorder traversal of the tree.
4. While traversing the root during the postorder traversal, one by one copy the values from the array arr to the nodes.
Postorder Traversal of Tree: 1 2 3 4 5 6 7
Time Complexity: O(n)
Auxiliary Space: O(n)
where, n is the number of nodes in the tree
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Convert min Heap to max Heap
- Difference between Binary Heap, Binomial Heap and Fibonacci Heap
- Difference between Min Heap and Max Heap
- Convert BST into a Min-Heap without using array
- Convert BST to Min Heap
- Convert a normal BST to Balanced BST
- Heap Sort for decreasing order using min heap
- Minimum element in a max heap
- Max Heap in Java
- K-th Greatest Element in a Max-Heap
- Max Heap in Python
- Why is Binary Heap Preferred over BST for Priority Queue?
- Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
- Two nodes of a BST are swapped, correct the BST | Set-2
- K'th Largest Element in BST when modification to BST is not allowed
- Find k-th smallest element in BST (Order Statistics in BST)
- Two nodes of a BST are swapped, correct the BST
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- Applications of Heap Data Structure
- Tournament Tree (Winner Tree) and Binary Heap
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.