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.