VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-normal-bst-balanced-bst/

⇱ Balance a Binary Search Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Balance a Binary Search Tree

Last Updated : 23 Jul, 2025

Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.

Examples: 

Input:

👁 Balance-a-Binary-Search-Tree

Output:

👁 Balance-a-Binary-Search-Tree-3


Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.

Input:

👁 Balance-a-Binary-Search-Tree-2


Output:

👁 Balance-a-Binary-Search-Tree-4

Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.

Approach:

The idea is to store the elements of the tree in an array using inorder traversal. Inorder traversal of a BST produces a sorted array. Once we have a sorted array, recursively construct a balanced BST by picking the middle element of the array as the root for each subtree.

Follow the steps below to solve the problem:

  • Traverse given BST in inorder and store result in an array. 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 in Sorted Array to Balanced BST.

Output
4 2 6 1 3 5 7 

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), as 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.


Comment
Article Tags: