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:
|
|
Outputs
|
|
OR
|
|
|
|
Example 2:
|
|
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. 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.
Here is the video explanation:
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is 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.