Wednesday, December 18, 2013

Convert Sorted Array to Binary Search Tree Leetcode

用了下recursion,很快就写出来了,值得一提的是,自从上班之后越来越懒了,看了下现在写题进度,已经大不如以前了,每天上班八小时之后回到家什么都不想干。为了去google必须挺住啊。
/**
 * 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 helper(num, 0, num.length-1);
    }
   
    public TreeNode helper(int[] num, int start, int end){
        if(end < start) return null;
       
        int mid = (start + end)/2;
        TreeNode temp = new TreeNode(num[mid]);
        temp.left = helper(num, start, mid-1);
        temp.right = helper(num, mid+1, end);
        return temp;
    }
}

No comments:

Post a Comment