Wednesday, February 19, 2014

Leetcode: Convert Sorted Array to Binary Search Tree

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

Solution:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        return sortedArrayToBST(num, 0, num.length-1);
    }
    
    public TreeNode sortedArrayToBST(int[] num, int begin, int end) {
        if (begin>end)
            return null;
        int midPoint= (begin+end)/2;
        TreeNode solution = new TreeNode(num[midPoint]);
        solution.left = sortedArrayToBST(num, begin, midPoint-1);
        solution.right = sortedArrayToBST(num, midPoint+1, end);
        return solution;
    }
}

No comments :

Post a Comment