Convert Sorted Array to Binary Search Tree

/**
 * 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) {
        if(num.length<=0) return null;
        
        TreeNode root=sort(num,0,num.length-1);
        return root;
        
        
    }
    public TreeNode sort(int[] num,int i,int j)
    {
        if(i>j) return null;
        if(i==j)
        {
            return new TreeNode(num[i]);
        }
        int mid=(i+j)>>1;
        TreeNode root=new TreeNode(num[mid]);
        root.left=sort(num,i,mid-1);
        root.right=sort(num,mid+1,j);
        
        return root;
        
        
        
        
    }
}
posted @ 2014-07-20 20:52  hansongjiang8  阅读(132)  评论(0编辑  收藏  举报