Balance a Binary Search Tree Problem
Description
LeetCode Problem 1382.
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.
Example 1:

Input: root = [1,null,2,null,3,null,4,null,null]
Output: [2,1,3,null,null,null,4]
Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.
Example 2:

Input: root = [2,1,3]
Output: [2,1,3]
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. 1 <= Node.val <= 10^5
Solution
Approach: In-Order Traversal, Then Rebuild
An in-order traversal of a BST lists its keys in sorted order. Once we have the sorted keys, building a balanced BST is the classic divide-and-conquer:
- Collect the keys with an in-order traversal into an array
values. build(lo, hi)makes a tree fromvalues[lo..hi]: the middle keyvalues[mid], withmid = (lo + hi) / 2, becomes the root,build(lo, mid - 1)its left subtree andbuild(mid + 1, hi)its right subtree. An empty range gives an empty tree.
The result is a BST because everything left of mid is smaller and everything right of it is larger. It is balanced because the two halves differ in size by at most one at every node, so their heights differ by at most one too.
Any balanced BST with the same keys is accepted, so there can be several right answers (Example 1 lists two).
Complexity: O(n) time and O(n) extra space for the array and the new nodes.
class Solution:
def balanceBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
values = [] # the keys in sorted order
def inorder(node: Optional[TreeNode]) -> None:
if node is not None:
inorder(node.left)
values.append(node.val)
inorder(node.right)
# Builds a balanced BST from values[lo..hi]: the middle key is the root.
def build(lo: int, hi: int) -> Optional[TreeNode]:
if lo > hi:
return None
mid = (lo + hi) // 2
return TreeNode(values[mid], build(lo, mid - 1), build(mid + 1, hi))
inorder(root)
return build(0, len(values) - 1)