leetcode 108 和leetcode 109 II

//感想:没啥上篇写完了

//思路:对于这道题109来说,就是数组变成了链表,其他没有变,我觉得非常不解,因为我想到的依旧是找中点,用快慢指针来找,

找到以后将链表分成两半,继续递归的去找,我就觉得这不是白费力气吗?用数组不好吗?非这么麻烦,关键去中点每次都要去遍历一遍链表,毕竟是个链表,查找起来就是慢啊,难道非要为了炫技而将效率降低吗?我还是算了吧。

我就是将整个链表遍历一遍放进数组中,然后跟上一题没啥区别了。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 /**
10  * Definition for a binary tree node.
11  * public class TreeNode {
12  *     int val;
13  *     TreeNode left;
14  *     TreeNode right;
15  *     TreeNode(int x) { val = x; }
16  * }
17  */
18 class Solution {
19     public TreeNode sortedListToBST(ListNode head) {
20         if(head==null)
21             return null;
22         ArrayList<Integer> list=new ArrayList<Integer>();
23         ListNode p=head;
24         while(p!=null)
25         {
26             list.add(p.val);
27             p=p.next;
28         }
29         return helper(list,0,list.size()-1);
30     }
31     public TreeNode helper(ArrayList<Integer> list,int l,int r)
32     {
33         if(l>r)
34             return null;
35         int mid=l+(r-l)/2;
36         TreeNode root=new TreeNode(list.get(mid));
37         root.left=helper(list,l,mid-1);
38         root.right=helper(list,mid+1,r);
39         return root;
40     }
41 }

猜你喜欢

转载自www.cnblogs.com/cold-windy/p/11779271.html
今日推荐