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:
Output:
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
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intvalue){data=value;left=nullptr;right=nullptr;}};// Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted ordervoidinorderTraversal(Node*root,vector<int>&arr){if(root==NULL)return;// first recur on left subtreeinorderTraversal(root->left,arr);// then copy the data of the nodearr.push_back(root->data);// now recur for right subtreeinorderTraversal(root->right,arr);}voidBSTToMaxHeap(Node*root,vector<int>&arr,int&i){if(root==NULL)return;// recur on left subtreeBSTToMaxHeap(root->left,arr,i);// recur on right subtreeBSTToMaxHeap(root->right,arr,i);// copy data at index 'i' of 'arr' to// the noderoot->data=arr[++i];}// Utility function to convert the given BST to// MAX HEAPvoidconvertToMaxHeapUtil(Node*root){// vector to store the data of all the// nodes of the BSTvector<int>arr;inti=-1;// inorder traversal to populate 'arr'inorderTraversal(root,arr);// BST to MAX HEAP conversionBSTToMaxHeap(root,arr,i);}// Function to Print Postorder Traversal of the treevoidpostorderTraversal(Node*root){if(!root)return;// recur on left subtreepostorderTraversal(root->left);// then recur on right subtreepostorderTraversal(root->right);// print the root's datacout<<root->data<<" ";}// Driver Codeintmain(){// BST formationNode*root=newNode(4);root->left=newNode(2);root->right=newNode(6);root->left->left=newNode(1);root->left->right=newNode(3);root->right->left=newNode(5);root->right->right=newNode(7);convertToMaxHeapUtil(root);cout<<"Postorder Traversal of Tree:"<<endl;postorderTraversal(root);return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intvalue){data=value;left=null;right=null;}}classGFG{// Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted orderstaticvoidinorderTraversal(Noderoot,ArrayList<Integer>arr){if(root==null)return;// first recur on left subtreeinorderTraversal(root.left,arr);// then copy the data of the nodearr.add(root.data);// now recur for right subtreeinorderTraversal(root.right,arr);}staticvoidBSTToMaxHeap(Noderoot,ArrayList<Integer>arr,int[]i){if(root==null)return;// recur on left subtreeBSTToMaxHeap(root.left,arr,i);// recur on right subtreeBSTToMaxHeap(root.right,arr,i);// copy data at index 'i' of 'arr' to// the noderoot.data=arr.get(++i[0]);}// Utility function to convert the given BST to// MAX HEAPstaticvoidconvertToMaxHeapUtil(Noderoot){// vector to store the data of all the// nodes of the BSTArrayList<Integer>arr=newArrayList<>();int[]i={-1};// inorder traversal to populate 'arr'inorderTraversal(root,arr);// BST to MAX HEAP conversionBSTToMaxHeap(root,arr,i);}// Function to Print Postorder Traversal of the treestaticvoidpostorderTraversal(Noderoot){if(root==null)return;// recur on left subtreepostorderTraversal(root.left);// then recur on right subtreepostorderTraversal(root.right);// print the root's dataSystem.out.print(root.data+" ");}// Driver Codepublicstaticvoidmain(String[]args){// BST formationNoderoot=newNode(4);root.left=newNode(2);root.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(5);root.right.right=newNode(7);convertToMaxHeapUtil(root);System.out.println("Postorder Traversal of Tree:");postorderTraversal(root);}}
Python
classNode:def__init__(self,value):self.data=valueself.left=Noneself.right=None# Function for the inorder traversal of the tree# so as to store the node values in 'arr' in# sorted orderdefinorderTraversal(root,arr):ifrootisNone:return# first recur on left subtreeinorderTraversal(root.left,arr)# then copy the data of the nodearr.append(root.data)# now recur for right subtreeinorderTraversal(root.right,arr)defBSTToMaxHeap(root,arr,i):ifrootisNone:return# recur on left subtreeBSTToMaxHeap(root.left,arr,i)# recur on right subtreeBSTToMaxHeap(root.right,arr,i)# copy data at index 'i' of 'arr' to# the nodei[0]+=1root.data=arr[i[0]]# Utility function to convert the given BST to# MAX HEAPdefconvertToMaxHeapUtil(root):# vector to store the data of all the# nodes of the BSTarr=[]i=[-1]# inorder traversal to populate 'arr'inorderTraversal(root,arr)# BST to MAX HEAP conversionBSTToMaxHeap(root,arr,i)# Function to Print Postorder Traversal of the treedefpostorderTraversal(root):ifnotroot:return# recur on left subtreepostorderTraversal(root.left)# then recur on right subtreepostorderTraversal(root.right)# print the root's dataprint(root.data,end=" ")# Driver Code# BST formationroot=Node(4)root.left=Node(2)root.right=Node(6)root.left.left=Node(1)root.left.right=Node(3)root.right.left=Node(5)root.right.right=Node(7)convertToMaxHeapUtil(root)print("Postorder Traversal of Tree:")postorderTraversal(root)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intvalue){data=value;left=null;right=null;}}classGFG{// Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted orderstaticvoidinorderTraversal(Noderoot,List<int>arr){if(root==null)return;// first recur on left subtreeinorderTraversal(root.left,arr);// then copy the data of the nodearr.Add(root.data);// now recur for right subtreeinorderTraversal(root.right,arr);}staticvoidBSTToMaxHeap(Noderoot,List<int>arr,refinti){if(root==null)return;// recur on left subtreeBSTToMaxHeap(root.left,arr,refi);// recur on right subtreeBSTToMaxHeap(root.right,arr,refi);// copy data at index 'i' of 'arr' to// the noderoot.data=arr[++i];}// Utility function to convert the given BST to// MAX HEAPstaticvoidconvertToMaxHeapUtil(Noderoot){// vector to store the data of all the// nodes of the BSTList<int>arr=newList<int>();inti=-1;// inorder traversal to populate 'arr'inorderTraversal(root,arr);// BST to MAX HEAP conversionBSTToMaxHeap(root,arr,refi);}// Function to Print Postorder Traversal of the treestaticvoidpostorderTraversal(Noderoot){if(root==null)return;// recur on left subtreepostorderTraversal(root.left);// then recur on right subtreepostorderTraversal(root.right);// print the root's dataConsole.Write(root.data+" ");}// Driver CodestaticvoidMain(){// BST formationNoderoot=newNode(4);root.left=newNode(2);root.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(5);root.right.right=newNode(7);convertToMaxHeapUtil(root);Console.WriteLine("Postorder Traversal of Tree:");postorderTraversal(root);}}
JavaScript
classNode{constructor(value){this.data=value;this.left=null;this.right=null;}}// Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted orderfunctioninorderTraversal(root,arr){if(root==null)return;// first recur on left subtreeinorderTraversal(root.left,arr);// then copy the data of the nodearr.push(root.data);// now recur for right subtreeinorderTraversal(root.right,arr);}functionBSTToMaxHeap(root,arr,i){if(root==null)return;// recur on left subtreeBSTToMaxHeap(root.left,arr,i);// recur on right subtreeBSTToMaxHeap(root.right,arr,i);// copy data at index 'i' of 'arr' to// the noderoot.data=arr[++i.value];}// Utility function to convert the given BST to// MAX HEAPfunctionconvertToMaxHeapUtil(root){// vector to store the data of all the// nodes of the BSTletarr=[];leti={value:-1};// inorder traversal to populate 'arr'inorderTraversal(root,arr);// BST to MAX HEAP conversionBSTToMaxHeap(root,arr,i);}// Function to Print Postorder Traversal of the treefunctionpostorderTraversal(root){if(!root)return;// recur on left subtreepostorderTraversal(root.left);// then recur on right subtreepostorderTraversal(root.right);// print the root's dataprocess.stdout.write(root.data+" ");}// Driver Code// BST formationletroot=newNode(4);root.left=newNode(2);root.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(5);root.right.right=newNode(7);convertToMaxHeapUtil(root);console.log("Postorder Traversal of Tree:");postorderTraversal(root);