leetcode 109. Convert Sorted List to Binary Search Tree
从一个list->BST 还要height balance
解题思路:
- 每次找中点作为root,将中点左边的作为左子树的节点,中点右边的作为右子树的节点。
但是考虑树要找中间节点, 所以我最开始的思路是: 将list 转换为一个vector, 然后就可以easy的找中点和左,右两个部分了。 但是有一个数据超时了。。。
class Solution {
public:
TreeNode * CreBST(vector<int> v, int s, int e)
{
if(s>e)
return NULL;
int mid=s+(e-s)/2;
TreeNode * T=new TreeNode (v[mid]);
T->left=CreBST(v,s, mid-1);
T->right=CreBST(v,mid+1, e);
return T;
}
TreeNode* sortedListToBST(ListNode* head) {
ListNode *l=head;
if(head==NULL)
return NULL;
vector<int> v;
while(l)
{
v.push_back(l->val);
l=l->next;
}
return CreBST(v, 0, v.size()-1);
}
};
所以不能先转换为vector。考虑直接在list 中找中点。。。
- list 找中点, 定义两个指针, 一个是另一个的两边速度,如果快的到达了终点,慢的就刚好在中点
class Solution {
public:
TreeNode * CreBST(ListNode * head, ListNode * Tail)
{
if(head==Tail)
return NULL;
ListNode * temp=head;
ListNode * mid=head;
while(temp!=Tail&& temp->next!=Tail)
{
temp=temp->next->next;
mid=mid->next;
}
TreeNode * T=new TreeNode (mid->val);
T->left=CreBST(head, mid);
T->right=CreBST(mid->next, Tail);
return T;
}
TreeNode * sortedListToBST(ListNode * head)
{
return CreBST(head, NULL);
}

浙公网安备 33010602011771号