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 INPUT Unbalanced BST 1 2 3 4 [1,null,2,null,3,null,4] Depth: 4 (skewed right) ALGORITHM STEPS 1 DFS Inorder Traversal Get sorted array: [1,2,3,4] 2 Find Middle Element mid = (0+3)/2 = 1 --> value 2 3 Build Subtrees Left: [1], Right: [3,4] 4 Recurse Apply to subtrees until done [1, 2, 3, 4] [1] 2 [3,4] Time: O(n) | Space: O(n) n = number of nodes FINAL RESULT Balanced BST 2 1 3 4 [2,1,3,null, null,null,4] OK - Balanced! Max depth diff: 1 Key Insight: Inorder traversal of BST gives sorted array. Building tree from sorted array by choosing middle element as root ensures minimum height and balanced structure. This divide-and-conquer approach guarantees depth difference of at most 1. TutorialsPoint - Balance a Binary Search Tree | DFS Inorder + Divide and Conquer Approach
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