VOOZH about

URL: https://www.geeksforgeeks.org/dsa/potd-solutions-15-oct-23-normal-bst-to-balanced-bst/

⇱ POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST

Last Updated : 23 Jul, 2025

View all POTD Solutions

Welcome to the daily solutions of our . We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Search Trees but will also help you build up problem-solving skills.

👁 GeeksforGeeks-POTD-Solutions-|-15-October-2023
GeeksforGeeks POTD Solutions | 15 October 2023

Given a Binary Search Tree, modify the given BST to be balanced and have the minimum possible height. Return the balanced BST.

Example 1:

👁 POTD-(2)

Example 2:

👁 ss
We recommend you to try this problem on our GeeksforGeeks Practice portal first, and maintain your streak to earn Geeksbits and other exciting prizes, before moving towards the solution.

The idea is to do the Inorder traversal of the Binary Search Tree and store the nodes in an array. The array will be sorted since the given tree is a BST. Then the middle element of the sorted array will be root of the new BST, ensuring that the left and right subtrees have nearly equal heights. The left subtree and right subtree can then be formed recursively.

Step-by-step approach:

  • Traverse the BST inorder and store each element into an array arr[] (The elements of inorder traversal would always be sorted).
  • Now, use this arr[] to create a balanced binary tree. To do this, find the middle element of the arr[] and make it root node.
  • All the elements on the left side of the middle element will be left subtree and all the elements on the right side of the middle element will be right subtree
  • Now, recursively build our left subtrees by again taking the middle element from the left side array and making it root node of left subtree
  • Similarly, build right subtree

Below is the implementation of above approach:

Time Complexity: O(N), As we traverse every node in the BST twice, where N is the number of nodes.
Auxiliary Space: O(N), As we have used a array to store all the nodes of the BST.

Comment