Given a BST (Binary Search Tree) that may be unbalanced, convert it into a balanced BST that has minimum possible height.
Examples :
Input:
30
/
20
/
10
Output:
20
/ \
10 30
Input:
4
/
3
/
2
/
1
Output:
3 3 2
/ \ / \ / \
1 4 OR 2 4 OR 1 3 OR ..
\ / \
2 1 4
Input:
4
/ \
3 5
/ \
2 6
/ \
1 7
Output:
4
/ \
2 6
/ \ / \
1 3 5 7
A Simple Solution is to traverse nodes in Inorder and one by one insert into a self-balancing BST like AVL tree. Time complexity of this solution is O(n Log n) and this solution doesn’t guarantee the minimum possible height as in the worst case the height of the AVL tree can be 1.44*log2n.
An Efficient Solution can be to construct a balanced BST in O(n) time with minimum possible height. Below are steps.
- Traverse given BST in inorder and store result in an array. This step takes O(n) time. Note that this array would be sorted as inorder traversal of BST always produces sorted sequence.
- Build a balanced BST from the above created sorted array using the recursive approach discussed here. This step also takes O(n) time as we traverse every element exactly once and processing an element takes O(1) time.
Below is the implementation of above steps.
C++
| // C++ program to convert a left unbalanced BST to// a balanced BST#include <bits/stdc++.h>usingnamespacestd;structNode{    intdata;    Node* left,  *right;};/* This function traverse the skewed binary tree and   stores its nodes pointers in vector nodes[] */voidstoreBSTNodes(Node* root, vector<Node*> &nodes){    // Base case    if(root==NULL)        return;    // Store nodes in Inorder (which is sorted    // order for BST)    storeBSTNodes(root->left, nodes);    nodes.push_back(root);    storeBSTNodes(root->right, nodes);}/* Recursive function to construct binary tree */Node* buildTreeUtil(vector<Node*> &nodes, intstart,                   intend){    // base case    if(start > end)        returnNULL;    /* Get the middle element and make it root */    intmid = (start + end)/2;    Node *root = nodes[mid];    /* Using index in Inorder traversal, construct       left and right subtress */    root->left  = buildTreeUtil(nodes, start, mid-1);    root->right = buildTreeUtil(nodes, mid+1, end);    returnroot;}// This functions converts an unbalanced BST to// a balanced BSTNode* buildTree(Node* root){    // Store nodes of given BST in sorted order    vector<Node *> nodes;    storeBSTNodes(root, nodes);    // Constructs BST from nodes[]    intn = nodes.size();    returnbuildTreeUtil(nodes, 0, n-1);}// Utility function to create a new nodeNode* newNode(intdata){    Node* node = newNode;    node->data = data;    node->left = node->right = NULL;    return(node);}/* Function to do preorder traversal of tree */voidpreOrder(Node* node){    if(node == NULL)        return;    printf("%d ", node->data);    preOrder(node->left);    preOrder(node->right);}// Driver programintmain(){    /* Constructed skewed binary tree is                10               /              8             /            7           /          6         /        5   */    Node* root = newNode(10);    root->left = newNode(8);    root->left->left = newNode(7);    root->left->left->left = newNode(6);    root->left->left->left->left = newNode(5);    root = buildTree(root);    printf("Preorder traversal of balanced "            "BST is : \n");    preOrder(root);    return0;} | 
Java
| // Java program to convert a left unbalanced BST to a balanced BSTimportjava.util.*;/* A binary tree node has data, pointer to left child   and a pointer to right child */classNode {    intdata;    Node left, right;    publicNode(intdata)     {        this.data = data;        left = right = null;    }}classBinaryTree {    Node root;    /* This function traverse the skewed binary tree and       stores its nodes pointers in vector nodes[] */    voidstoreBSTNodes(Node root, Vector<Node> nodes)     {        // Base case        if(root == null)            return;        // Store nodes in Inorder (which is sorted        // order for BST)        storeBSTNodes(root.left, nodes);        nodes.add(root);        storeBSTNodes(root.right, nodes);    }    /* Recursive function to construct binary tree */    Node buildTreeUtil(Vector<Node> nodes, intstart,            intend)     {        // base case        if(start > end)            returnnull;        /* Get the middle element and make it root */        intmid = (start + end) / 2;        Node node = nodes.get(mid);        /* Using index in Inorder traversal, construct           left and right subtress */        node.left = buildTreeUtil(nodes, start, mid - 1);        node.right = buildTreeUtil(nodes, mid + 1, end);        returnnode;    }    // This functions converts an unbalanced BST to    // a balanced BST    Node buildTree(Node root)     {        // Store nodes of given BST in sorted order        Vector<Node> nodes = newVector<Node>();        storeBSTNodes(root, nodes);        // Constructs BST from nodes[]        intn = nodes.size();        returnbuildTreeUtil(nodes, 0, n - 1);    }    /* Function to do preorder traversal of tree */    voidpreOrder(Node node)     {        if(node == null)            return;        System.out.print(node.data + " ");        preOrder(node.left);        preOrder(node.right);    }    // Driver program to test the above functions    publicstaticvoidmain(String[] args)     {         /* Constructed skewed binary tree is                10               /              8             /            7           /          6         /        5   */        BinaryTree tree = newBinaryTree();        tree.root = newNode(10);        tree.root.left = newNode(8);        tree.root.left.left = newNode(7);        tree.root.left.left.left = newNode(6);        tree.root.left.left.left.left = newNode(5);        tree.root = tree.buildTree(tree.root);        System.out.println("Preorder traversal of balanced BST is :");        tree.preOrder(tree.root);    }}// This code has been contributed by Mayank Jaiswal(mayank_24) | 
Python3
| # Python3 program to convert a left # unbalanced BST to a balanced BST importsysimportmath# A binary tree node has data, pointer to left child # and a pointer to right child classNode:    def__init__(self,data):        self.data=data        self.left=None        self.right=None# This function traverse the skewed binary tree and # stores its nodes pointers in vector nodes[]defstoreBSTNodes(root,nodes):        # Base case    ifnotroot:        return        # Store nodes in Inorder (which is sorted     # order for BST)     storeBSTNodes(root.left,nodes)    nodes.append(root)    storeBSTNodes(root.right,nodes)# Recursive function to construct binary tree defbuildTreeUtil(nodes,start,end):        # base case     ifstart>end:        returnNone    # Get the middle element and make it root     mid=(start+end)//2    node=nodes[mid]    # Using index in Inorder traversal, construct     # left and right subtress    node.left=buildTreeUtil(nodes,start,mid-1)    node.right=buildTreeUtil(nodes,mid+1,end)    returnnode# This functions converts an unbalanced BST to # a balanced BSTdefbuildTree(root):        # Store nodes of given BST in sorted order     nodes=[]    storeBSTNodes(root,nodes)    # Constructs BST from nodes[]     n=len(nodes)    returnbuildTreeUtil(nodes,0,n-1)# Function to do preorder traversal of treedefpreOrder(root):    ifnotroot:        return    print("{} ".format(root.data),end="")    preOrder(root.left)    preOrder(root.right)# Driver codeif__name__=='__main__':    # Constructed skewed binary tree is     #         10     #         /     #         8     #         /     #     7     #     /     #     6     #     /     # 5     root =Node(10)    root.left =Node(8)    root.left.left =Node(7)    root.left.left.left =Node(6)    root.left.left.left.left =Node(5)    root =buildTree(root)    print("Preorder traversal of balanced BST is :")    preOrder(root)    # This code has been contributed by Vikash Kumar 37 | 
C#
| usingSystem;usingSystem.Collections.Generic;// C# program to convert a left unbalanced BST to a balanced BST /* A binary tree node has data, pointer to left child    and a pointer to right child */publicclassNode{    publicintdata;    publicNode left, right;    publicNode(intdata)    {        this.data = data;        left = right = null;    }}publicclassBinaryTree{    publicNode root;    /* This function traverse the skewed binary tree and        stores its nodes pointers in vector nodes[] */    publicvirtualvoidstoreBSTNodes(Node root, List<Node> nodes)    {        // Base case         if(root == null)        {            return;        }        // Store nodes in Inorder (which is sorted         // order for BST)         storeBSTNodes(root.left, nodes);        nodes.Add(root);        storeBSTNodes(root.right, nodes);    }    /* Recursive function to construct binary tree */    publicvirtualNode buildTreeUtil(List<Node> nodes, intstart, intend)    {        // base case         if(start > end)        {            returnnull;        }        /* Get the middle element and make it root */        intmid = (start + end) / 2;        Node node = nodes[mid];        /* Using index in Inorder traversal, construct            left and right subtress */        node.left = buildTreeUtil(nodes, start, mid - 1);        node.right = buildTreeUtil(nodes, mid + 1, end);        returnnode;    }    // This functions converts an unbalanced BST to     // a balanced BST     publicvirtualNode buildTree(Node root)    {        // Store nodes of given BST in sorted order         List<Node> nodes = newList<Node>();        storeBSTNodes(root, nodes);        // Constructs BST from nodes[]         intn = nodes.Count;        returnbuildTreeUtil(nodes, 0, n - 1);    }    /* Function to do preorder traversal of tree */    publicvirtualvoidpreOrder(Node node)    {        if(node == null)        {            return;        }        Console.Write(node.data + " ");        preOrder(node.left);        preOrder(node.right);    }    // Driver program to test the above functions     publicstaticvoidMain(string[] args)    {         /* Constructed skewed binary tree is                 10                /               8              /             7            /           6          /         5   */        BinaryTree tree = newBinaryTree();        tree.root = newNode(10);        tree.root.left = newNode(8);        tree.root.left.left = newNode(7);        tree.root.left.left.left = newNode(6);        tree.root.left.left.left.left = newNode(5);        tree.root = tree.buildTree(tree.root);        Console.WriteLine("Preorder traversal of balanced BST is :");        tree.preOrder(tree.root);    }}  //  This code is contributed by Shrikant13 | 
Javascript
| <script>    // JavaScript program to convert a left    // unbalanced BST to a balanced BST        class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }        let root;      /* This function traverse the skewed binary tree and       stores its nodes pointers in vector nodes[] */    functionstoreBSTNodes(root, nodes)     {        // Base case        if(root == null)            return;          // Store nodes in Inorder (which is sorted        // order for BST)        storeBSTNodes(root.left, nodes);        nodes.push(root);        storeBSTNodes(root.right, nodes);    }      /* Recursive function to construct binary tree */    functionbuildTreeUtil(nodes, start, end)     {        // base case        if(start > end)            returnnull;          /* Get the middle element and make it root */        let mid = parseInt((start + end) / 2, 10);        let node = nodes[mid];          /* Using index in Inorder traversal, construct           left and right subtress */        node.left = buildTreeUtil(nodes, start, mid - 1);        node.right = buildTreeUtil(nodes, mid + 1, end);          returnnode;    }      // This functions converts an unbalanced BST to    // a balanced BST    functionbuildTree(root)     {        // Store nodes of given BST in sorted order        let nodes = [];        storeBSTNodes(root, nodes);          // Constructs BST from nodes[]        let n = nodes.length;        returnbuildTreeUtil(nodes, 0, n - 1);    }      /* Function to do preorder traversal of tree */    functionpreOrder(node)     {        if(node == null)            return;        document.write(node.data + " ");        preOrder(node.left);        preOrder(node.right);    }        /* Constructed skewed binary tree is                  10                 /                8               /              7             /            6           /          5   */    root = newNode(10);    root.left = newNode(8);    root.left.left = newNode(7);    root.left.left.left = newNode(6);    root.left.left.left.left = newNode(5);    root = buildTree(root);    document.write("Preorder traversal of balanced BST is :"+ "</br>");    preOrder(root);    </script> | 
Preorder traversal of balanced BST is : 7 5 6 8 10
Time Complexity: O(n), As we are just traversing the tree twice. Once in inorder traversal and then in construction of the balanced tree.
Auxiliary space: O(n), The extra space is used to store the nodes of the inorder traversal in the vector. Also the extra space taken by recursion call stack is O(h) where h is the height of the tree.
This article is contributed Aditya Goel. If you likeneveropen and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







