/** * 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==null||num.length==0){ return null; } int length=num.length; TreeNode treenode=sortedArrayToBST(num,0,length-1);//我每次总是忘记减一,以后要记住 return treenode ; } private TreeNode sortedArrayToBST(int[] num, int star, int tail) { if(star>tail){ return null; } int mid=star+(tail-star+1)/2; TreeNode root=new TreeNode(num[mid]); root.left=sortedArrayToBST(num,star,mid-1); root.right=sortedArrayToBST(num,mid+1,tail); return root; } }
时间: 2024-10-03 06:17:57