s*****1 发帖数: 134 | 1 这题和上面一题(convert vector)是不是思路一样?
我就先把list转成vector做了
有没有专门给list的方法? | d*********g 发帖数: 154 | | P*******U 发帖数: 203 | 3 不用转的,可以直接搞
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null)
return null;
if(head.next == null)
return new TreeNode(head.val);
ListNode head1, head2;
head1 = head;
head2 = head;
while(head2!=null && head2.next!=null){
head1 = head1.next;
head2 = head2.next.next;
}
ListNode temp = head;
while(temp.next.val!=head1.val){
temp = temp.next;
}
temp.next = null;
TreeNode root = new TreeNode(head1.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(head1.next);
return root;
}
} | s*****1 发帖数: 134 | 4 hi, 谢谢2位楼上回复!
第一个的链接很有效,太感谢了!
第二个的算法很精妙,虽然复杂度可能不是linear,但是也给我提了个醒,谢谢啦 |
|