1 public TreeNode sortedListToBST(ListNode head) { 2 if(head==null) return new TreeNode(0); 3 ArrayList<TreeNode> arr=new ArrayList<TreeNode>(); 4 while(head!=null) 5 { 6 arr.add(new TreeNode(head.val)); 7 head=head.next; 8 } 9 10 return BST(arr,0,arr.size()-1); 11 } 12 TreeNode BST(ArrayList<TreeNode> list,int start,int end) 13 { 14 if(start>=end) 15 { 16 return list.get(start); 17 } 18 else 19 { 20 int mid=start+(end-start)/2; 21 TreeNode root=list.get(mid); 22 root.left=BST(list,start,mid-1); 23 root.right=BST(list,mid+1,end); 24 25 return root; 26 } 27 }
时间: 2024-10-01 07:16:28