Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.Â
Examples
Input:
Output:
Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree.Â
Using Inorder Traversal & Sorting - O(n log n) Time and O(n) Space
Use the fact that inorder traversal of a BST is sorted. Store all node values using inorder, sort them, then refill the tree using inorder traversal so it becomes a BST without changing its structure.
Perform inorder traversal and store values in a vector and sort the vector
Traverse tree again using inorder and replace node values with sorted values using an index variable.
Below is the implementation of the above approach:
C++
// C++ Program to convert binary // tree to binary search tree.#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Inorder traversal to store the nodes in a vectorvoidinorder(Node*root,vector<int>&nodes){if(root==nullptr){return;}inorder(root->left,nodes);nodes.push_back(root->data);inorder(root->right,nodes);}// Inorder traversal to convert tree// to BST.voidconstructBST(Node*root,vector<int>nodes,int&index){if(root==nullptr)return;constructBST(root->left,nodes,index);// Update root valueroot->data=nodes[index++];constructBST(root->right,nodes,index);}// Function to convert a binary tree to a binary search treeNode*binaryTreeToBST(Node*root){vector<int>nodes;inorder(root,nodes);// sort the nodessort(nodes.begin(),nodes.end());intindex=0;constructBST(root,nodes,index);returnroot;}// Function to print the inorder traversal of a binary treevoidprintInorder(Node*root){if(root==NULL){return;}printInorder(root->left);cout<<root->data<<" ";printInorder(root->right);}intmain(){// Creating the tree// 10// / \ // 2 7// / \ // 8 4Node*root=newNode(10);root->left=newNode(2);root->right=newNode(7);root->left->left=newNode(8);root->left->right=newNode(4);Node*ans=binaryTreeToBST(root);printInorder(ans);return0;}
Java
// Java Program to convert binary // tree to binary search tree.importjava.util.ArrayList;importjava.util.Collections;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Inorder traversal to store the nodes in a vectorstaticvoidinorder(Noderoot,ArrayList<Integer>nodes){if(root==null){return;}inorder(root.left,nodes);nodes.add(root.data);inorder(root.right,nodes);}// Inorder traversal to convert tree to BST.staticvoidconstructBST(Noderoot,ArrayList<Integer>nodes,int[]index){if(root==null)return;constructBST(root.left,nodes,index);// Update root valueroot.data=nodes.get(index[0]);index[0]++;constructBST(root.right,nodes,index);}// Function to convert a binary tree to a binary search treestaticNodebinaryTreeToBST(Noderoot){ArrayList<Integer>nodes=newArrayList<>();inorder(root,nodes);// sort the nodesCollections.sort(nodes);int[]index={0};constructBST(root,nodes,index);returnroot;}// Function to print the inorder traversal of a binary treestaticvoidprintInorder(Noderoot){if(root==null){return;}printInorder(root.left);System.out.print(root.data+" ");printInorder(root.right);}publicstaticvoidmain(String[]args){// Creating the tree// 10// / \// 2 7// / \// 8 4Noderoot=newNode(10);root.left=newNode(2);root.right=newNode(7);root.left.left=newNode(8);root.left.right=newNode(4);Nodeans=binaryTreeToBST(root);printInorder(ans);}}
Python
# Python Program to convert binary # tree to binary search tree.classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Inorder traversal to store the nodes in a vectordefinorder(root,nodes):ifrootisNone:returninorder(root.left,nodes)nodes.append(root.data)inorder(root.right,nodes)# Inorder traversal to convert tree to BST.defconstructBst(root,nodes,index):ifrootisNone:returnconstructBst(root.left,nodes,index)# Update root valueroot.data=nodes[index[0]]index[0]+=1constructBst(root.right,nodes,index)# Function to convert a binary tree to a binary search treedefbinaryTreeToBst(root):nodes=[]inorder(root,nodes)# sort the nodesnodes.sort()index=[0]constructBst(root,nodes,index)returnroot# Function to print the inorder traversal of a binary treedefprintInorder(root):ifrootisNone:returnprintInorder(root.left)print(root.data,end=" ")printInorder(root.right)if__name__=="__main__":# Creating the tree# 10# / \# 2 7# / \# 8 4root=Node(10)root.left=Node(2)root.right=Node(7)root.left.left=Node(8)root.left.right=Node(4)ans=binaryTreeToBst(root)printInorder(ans)
C#
// C# Program to convert binary // tree to binary search tree.usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Inorder traversal to store the nodes in a liststaticvoidInorder(Noderoot,List<int>nodes){if(root==null){return;}Inorder(root.left,nodes);nodes.Add(root.data);Inorder(root.right,nodes);}// Inorder traversal to convert tree to BST.staticvoidConstructBST(Noderoot,List<int>nodes,refintindex){if(root==null)return;ConstructBST(root.left,nodes,refindex);// Update root valueroot.data=nodes[index];index++;ConstructBST(root.right,nodes,refindex);}// Function to convert a binary tree to a binary search treestaticNodeBinaryTreeToBST(Noderoot){List<int>nodes=newList<int>();Inorder(root,nodes);// sort the nodesnodes.Sort();intindex=0;ConstructBST(root,nodes,refindex);returnroot;}// Function to print the inorder traversal of a binary treestaticvoidPrintInorder(Noderoot){if(root==null){return;}PrintInorder(root.left);Console.Write(root.data+" ");PrintInorder(root.right);}staticvoidMain(){// Creating the tree// 10// / \// 2 7// / \// 8 4Noderoot=newNode(10);root.left=newNode(2);root.right=newNode(7);root.left.left=newNode(8);root.left.right=newNode(4);Nodeans=BinaryTreeToBST(root);PrintInorder(ans);}}
JavaScript
// JavaScript Program to convert binary // tree to binary search tree.classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Inorder traversal to store the nodes in a vectorfunctioninorderTrav(root,nodes){if(root===null){return;}inorderTrav(root.left,nodes);nodes.push(root.data);inorderTrav(root.right,nodes);}// Inorder traversal to convert tree to BST.functionconstructBST(root,nodes,index){if(root===null)return;constructBST(root.left,nodes,index);// Update root valueroot.data=nodes[index[0]];index[0]++;constructBST(root.right,nodes,index);}// Function to convert a binary tree to a binary search treefunctionbinaryTreeToBST(root){letnodes=[];inorderTrav(root,nodes);// sort the nodesnodes.sort((a,b)=>a-b);letindex=[0];constructBST(root,nodes,index);returnroot;}// Function to print the inorder traversal of a binary treefunctionprintInorder(root){if(root===null){return;}printInorder(root.left);console.log(root.data);printInorder(root.right);}// Creating the tree// 10// / \// 2 7// / \// 8 4letroot=newNode(10);root.left=newNode(2);root.right=newNode(7);root.left.left=newNode(8);root.left.right=newNode(4);letans=binaryTreeToBST(root);printInorder(ans);