![]() |
VOOZH | about |
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.
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:
👁 ssThe 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:
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.