convert-sorted-list-to-binary-se

2019-05-30  本文已影响0人  DaiMorph
class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        return create(head,NULL);
    }
    TreeNode*create(ListNode*head,ListNode*tail)
    {
        if(head==tail)return NULL;
        ListNode*slow=head,*fast=head;
        while(fast!=tail&&fast->next!=tail)slow=slow->next,fast=fast->next->next;
        TreeNode*root=new TreeNode(slow->val);
        root->left=create(head,slow);
        root->right=create(slow->next,tail);
        return root;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读