[LeetCode] 108. Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Thought process:
Divide and conquer, recursively attach left sub-tree and right sub-tree to root:
  1. Base case: when the array is empty, return null.
  2. Recurrence: root is at array's length / 2. Left sub-tree is the root of the first half of the array. Right sub-tree is the root of the second half of the array.

Solution:

 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
26
27
28
29
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return sortedArrayToBST(nums, 0, nums.length);
    }
    
    private TreeNode sortedArrayToBST(int[] nums, int start, int end) {
        if (start == end) {
            return null;
        }
        
        int mid = start + (end - start) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        TreeNode left = sortedArrayToBST(nums, start, mid);
        TreeNode right = sortedArrayToBST(nums, mid + 1, end);
        root.left = left;
        root.right = right;
        
        return root;
    }
}
Time complexity:
Say the array contains n elements. Every element is visited exactly once. So the overall time complexity is O(n).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula