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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code