Problem
Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Examples
Example 1:
|
|
These are the two height-balanced binary tree, with height = 3
:
|
|
OR
|
|
Note, that we may also get skewed binary search tree, but we don’t want that, height = 6 is not minimum
|
|
Solution
Why minimal height is important?
We can perform a linear scan of the array, using the first element as the root and inserting subsequent elements into the tree. However, this would result in a skewed tree, with all nodes on one side, causing the tree height to equal the number of elements. Our goal is to keep the tree as balanced as possible.
Definition: Balanced Binary Search Tree BBST Data Structures
Method 1 - Recursive Preorder Traversal
Here are the steps:
- Find the middle element of the array.
- Make it root to ensure half of the array elements are on the left and half on the right.
- Recursively process the left half of the array and set it as
root.left
. - Recursively process the right half of the array and set it as
root.right
. - Return the root.
Here is the video explanation:
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of array - 🧺 Space complexity:
O(log n)
as log n is the height of the tree.