您的位置:首页 > 其它

leetcode刷题,总结,记录,备忘109

2016-04-24 00:51 288 查看
leetcode109


Convert Sorted List to Binary Search Tree

 

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Subscribe to see which companies asked this question
使用二分法,然后分别分为2个分支,进行递归操作,还是比较简单的,但是貌似算法耗时有点多,40ms,,但是在leetcode提交通过的解决方案中排的比较靠后。。
/**
* 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) {}
* };
*/
class Solution {
public:
TreeNode * result;

void funciton(vector<int> vi, TreeNode * root)
{
if (root == NULL)
{
root = new TreeNode(0);
result = root;
}

if (vi.size() == 1)
{
root->val = vi[0];
root->left = NULL;
root->right = NULL;
}
else if (vi.size() == 2)
{
root->val = vi[0];
root->left = NULL;
root->right = new TreeNode(vi[1]);
}
else
{
int mid = vi.size() / 2;
root->val = vi[mid];
root->left = new TreeNode(0);
root->right = new TreeNode(0);
vector<int> vl(vi.begin(), vi.begin() + mid);
vector<int> vr(vi.begin() + mid + 1, vi.end());
funciton(vl, root->left);
funciton(vr, root->right);
}
}

TreeNode* sortedListToBST(ListNode* head) {
vector<int> vi;
if (head == NULL)
{
return NULL;
}

while (head)
{
vi.push_back(head->val);
head = head->next;
}

funciton(vi, NULL);

return result;
}
};然后在讨论区看到一个解法,受到的启发,还记得leetcode之前有个判断1个链表是否是循环的题,使用快慢指针,这个方法就是使用快慢指针,找到中间的指针,然后也是1分为2,递归做二分法,比较巧妙的做法,感觉比我自己想 的解法更好,下面也把这个解决方法贴出来。
/**
* 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) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if (head == NULL)
{
return NULL;
}

ListNode * fast = head;
ListNode * slow = head;
ListNode * pre = NULL;

while (fast && fast->next)
{
fast = fast->next->next;
pre = slow;
slow = slow->next;
}

if (pre)
{
pre->next = NULL;
}
else
{
head = NULL;
}

TreeNode * root = new TreeNode(slow->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);

return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: