首页 > 代码库 > Convert Sorted Array to Binary Search Tree

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;                                    }}