Day14: [LeetCode中等] 09. 有序链表转换二叉搜索树
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/
思路1:
这题应该有很多种方法,可以直接构造一个平衡二叉树,然后把遍历链表挨个把值插入,但构造平衡二叉树是一件挺麻烦的事,而且这样就浪费了有序链表这个条件。这里我用的方法是二分查找法,先把链表转存到数组中,然后通过数组下标二分查找,以递归的方式完成插入,简单快捷。从开始写到AC大概15-20分钟就完事了。
值得一提的是,我终于知道了 为什么某些测试用例下,执行代码返回结果正确,但提交解答却出错了,之前LeetCode就出过这种问题,这里有官方解释。
思路2:
这个是我看题解里别人的思路,不用转存为数组了,比我的好,学习一哈,用的是快慢指针+递归的方法。具体看这里。
思路1代码:
dirty code凑合看吧
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
TreeNode* f(int left,int right,vector<int> &v){
if(left>right) return NULL;
int mid=(left+right)/2;
TreeNode *q=new TreeNode(v[mid]);
q->left=f(left,mid-1,v);
q->right=f(mid+1,right,v);
return q;
}
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
vector<int> v;
int Len=0;
if(!head) return (TreeNode*)NULL;
auto p=head;
while(p){
v.push_back(p->val);
p=p->next;
}
Len=v.size();
return f(0,Len-1,v);
}
};
思路2代码:
class Solution {
//快慢指针
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
if (head.next == null) return new TreeNode(head.val);
// p 一次前进一格,q 前进两格,pre 是 p 前一个
ListNode p = head.next, q = head.next.next, pre = head;
while (q != null && q.next != null) {
pre = pre.next;
p = p.next;
q = q.next.next;
}
pre.next = null;
// 链表被分成三段,再递归构造
TreeNode root = new TreeNode(p.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(p.next);
return root;
}
}