标签:另一个 highlight 部分 node ted 转换 思路 int convert
从一个list->BST 还要height balance
解题思路:
但是考虑树要找中间节点, 所以我最开始的思路是: 将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 中找中点。。。
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);
}
leetcode 109. Convert Sorted List to Binary Search Tree
标签:另一个 highlight 部分 node ted 转换 思路 int convert
原文地址:http://www.cnblogs.com/fanhaha/p/7397660.html