My accepted CPP answer, clear and easy to understand


  • 6
    W
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head) {
            return buildTree(head,nullptr);
        }
        TreeNode* buildTree(ListNode* head, ListNode* afterLast){
            if(head==afterLast)
            return nullptr;
            ListNode* fast=head;
            ListNode* slow=head;
            while(fast!=afterLast&&fast->next!=afterLast){
                slow=slow->next;
                fast=fast->next->next;
            }
            TreeNode* root=new TreeNode(slow->val);
            root->left=buildTree(head,slow);
            root->right=buildTree(slow->next,afterLast);
            return root;
        }
    };

  • 0
    Z

    concise "up to bottom" approach, well down


  • 0
    R

    Hmm.. I applied same algorithm in python, but resulted in TLE. Looks like it works for CPP.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.