VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-bst-to-max-heap/

⇱ Convert BST to Max Heap - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert BST to Max Heap

Last Updated : 28 May, 2026

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. 

Examples: 

Input:

👁 frame_3348


Output:

👁 frame_3349


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.

Prerequisites: Binary Search Tree | Heaps

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

Output
Postorder Traversal of Tree:
1 2 3 4 5 6 7 
Comment
Article Tags: