15. Normal BST to Balanced BST
The problem can be found at the following link: Question Link
My Approach
To convert a normal Binary Search Tree (BST) into a balanced BST, I follow these steps:
Perform an in-order traversal of the original BST and store the nodes in an array (
arr
) in sorted order.Create a new BST from the sorted
arr
by selecting the middle element as the root node, and then recursively constructing left and right subtrees.Return the new balanced BST.
Time and Auxiliary Space Complexity
Time Complexity:
O(N)
, whereN
is the number of nodes in the original BST. This is because both the in-order traversal and the creation of the balanced BST are linear operations.Auxiliary Space Complexity:
O(N)
, whereN
is the number of nodes in the original BST. The auxiliary space is used for thearr
vector, which stores all the nodes during in-order traversal.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated