Balance a Binary Search Tree
MediumUpdated: Aug 2, 2025
Practice on:
Problem
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.
Examples
Example 1:
1
\
2
\
3
\
4
Outputs
2
/ \
1 3
\
4
OR
3
/ \
1 4
\
2
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]
Solution
Method 1 - Inorder traversal to sorted array to balanced BST
We can use the solution from [Convert Sorted Array to height-balanced Binary Search Tree](convert-sorted-array-to-height-balanced-binary-search-tree). The idea is:
- Traverse binary tree in-order to get sorted array.
- Convert the sorted array to height-balanced BST using [Convert Sorted Array to height-balanced Binary Search Tree](convert-sorted-array-to-height-balanced-binary-search-tree).
Here is the video explanation: <div class="youtube-embed"><iframe src="https://www.youtube.com/embed/YZQKRBKpiTM" frameborder="0" allowfullscreen></iframe></div>
Code
Java
Because in java, we should know the length of the array to create, we will use List instead.
class Solution {
List<TreeNode> sortedList = new ArrayList<>();
public TreeNode balanceBST(TreeNode root) {
inorderTraverse(root);
return sortedListToBST(0, sortedList.size() - 1);
}
void inorderTraverse(TreeNode root) {
if (root == null){
return;
}
inorderTraverse(root.left);
sortedList.add(root);
inorderTraverse(root.right);
}
TreeNode sortedListToBST(int start, int end) {
if (start > end) {
return null;
}
int mid = (start + end) / 2;
TreeNode root = sortedList.get(mid);
root.left = sortedListToBST(start, mid - 1);
root.right = sortedListToBST(mid + 1, end);
return root;
}
}
Complexity
- ⏰ Time complexity:
O(n)wherenis number of nodes in BST. It takesO(n)time to do inorder traversal, and thenO(n)time to convert array to height-balanced BST. - 🧺 Space complexity:
O(n)assuming recursion stack and also for storing sorted array.