04.02. Minimum Height Tree
Description
Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.
Example:
Given sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5]οΌwhich represents the following tree: 0 / \ -3 9 / / -10 5
Solutions
Solution 1: Recursion
We design a function dfs(l, r)
, which constructs a subtree from l
to r
. Therefore, the answer is dfs(0, len(nums) - 1)
.
The execution process of the function dfs(l, r)
is as follows:
- If
l > r
, returnNone
. - Otherwise, we calculate the middle position
mid = (l + r) / 2
, then construct the root node, the left subtree isdfs(l, mid - 1)
, and the right subtree isdfs(mid + 1, r)
. - Finally, return the root node.
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|