w***y 发帖数: 6251 | 1 我基本上是照着答案implement的啊,为什么总是超时呢?
大牛帮我看看问题在哪里吧
public ListNode list;
public TreeNode sortedListToBST(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head==null) return null;
ListNode p = head;
int cnt = 1;
while(p.next !=null){
cnt++;
}
list=head;
return _sortedListToBST(0,cnt-1);
}
TreeNode _sortedListToBST( int s, int e){
if (s > e) return null;
int mid=s+(e-s)/2;
TreeNode left=_sortedListToBST(s, mid-1);
TreeNode node=new TreeNode(list.val);
node.left=left;
list=list.next;
node.right=_sortedListToBST(mid+1, e);
return node;
}
|
|