Sunday, November 1, 2015

[leetcode] Convert Sorted Array to Binary Search Tree

Construct a balance binary search tree from a sorted array.
Recursively use the mid number as the root

 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; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return recur(0, nums.length-1, nums);
    }
    
    private TreeNode recur(int start, int end, int[] nums){
        if (start > end){
            return null;
        }
        int mid = (start+end)/2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = recur(start, mid-1, nums);
        root.right = recur(mid+1, end, nums);
        return root;
    }
}

No comments:

Post a Comment