Skip to content

04.02. Minimum Height Tree

Description

Given a sorted (increasing order) array with unique integer elements, write an algo­rithm 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:

  1. If l > r, return None.
  2. Otherwise, we calculate the middle position mid = (l + r) / 2, then construct the root node, the left subtree is dfs(l, mid - 1), and the right subtree is dfs(mid + 1, r).
  3. 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
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        def dfs(l: int, r: int) -> TreeNode:
            if l > r:
                return None
            mid = (l + r) >> 1
            return TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r))

        return dfs(0, len(nums) - 1)
 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
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int[] nums;

    public TreeNode sortedArrayToBST(int[]