BST to Balanced BST - Problem

Given an unbalanced Binary Search Tree (BST), convert it into a height-balanced BST.

A height-balanced BST is defined as a binary tree where the depth of the left and right subtrees of every node differs by at most 1.

The converted BST should maintain the BST property: for every node, all values in the left subtree are smaller, and all values in the right subtree are larger.

Note: Return the root of the balanced BST. Multiple valid balanced BSTs are possible - return any one of them.

Input & Output

Example 1 — Unbalanced Right-Heavy BST
$ Input: root = [1,null,2,null,3,null,4,null,null]
Output: [2,1,3,null,null,null,4]
💡 Note: The original BST is completely right-heavy like a linked list. After balancing, node 2 becomes root with 1 on left and 3 on right, with 4 as right child of 3.
Example 2 — Simple Unbalanced Tree
$ Input: root = [2,1,3]
Output: [2,1,3]
💡 Note: The tree is already balanced with height difference ≤ 1 between subtrees, so no changes needed.
Example 3 — Left-Heavy Chain
$ Input: root = [4,3,null,2,null,1]
Output: [2,1,3,null,null,null,4]
💡 Note: Original tree is left-heavy chain. After balancing, node 2 becomes root with perfect balance.

Constraints

  • 1 ≤ Number of nodes ≤ 104
  • 1 ≤ Node.val ≤ 104
  • The input tree is a valid BST

Visualization

Tap to expand
INPUTALGORITHMRESULTUnbalanced BSTIn-order + Balanced BuildHeight-Balanced BST1234Right-heavy chainHeight = 41In-order Traversal2Extract: [1, 2, 3, 4]3Choose middle: 24Build balanced tree2134Perfectly balancedHeight = 3Key Insight:In-order traversal gives sorted values, then choosing middle elementsas roots guarantees perfect balance in linear time!TutorialsPoint - BST to Balanced BST | Optimal In-order + Balanced Construction
Asked in
Amazon 45 Microsoft 38 Google 32 Facebook 28
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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