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.

Input & Output

Example 1 — Right Skewed Tree
$ Input: root = [1,null,2,null,3,null,4,null,null]
Output: [2,1,3,null,null,null,4]
💡 Note: Original tree is completely right-skewed. After balancing, node 2 becomes root with 1 as left child and 3 as right child, with 4 as right child of 3.
Example 2 — Left Skewed Tree
$ Input: root = [2,1,3]
Output: [2,1,3]
💡 Note: Tree is already balanced - depth difference between left and right subtrees is at most 1, so no changes needed.
Example 3 — Complex Unbalanced
$ Input: root = [1,null,2,null,3,null,4,null,5]
Output: [3,2,4,1,null,null,5]
💡 Note: Completely unbalanced chain becomes balanced with 3 as root, 2 on left (with 1 as left child), and 4 on right (with 5 as right child).

Constraints

  • The number of nodes in the tree is in the range [1, 104].
  • 1 ≤ Node.val ≤ 105

Visualization

Tap to expand
Balance a Binary Search Tree: Transform Unbalanced → Balanced1234Unbalanced InputHeight = 4Balance2134Balanced OutputHeight = 3Same values [1,2,3,4], but balanced structure!
Understanding the Visualization
1
Input
Unbalanced BST (right-skewed chain)
2
Process
Extract sorted values and rebuild balanced
3
Output
Perfectly balanced BST with same values
Key Takeaway
🎯 Key Insight: Use BST property - inorder traversal gives sorted array, then rebuild balanced from middle
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
98.4K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen