109. 有序鏈表轉換二叉搜索樹

找中點然後採用分治法。

class Solution {

public:

    TreeNode* sortedListToBST(ListNode* head) {

        if(head == NULL) return NULL;

        if(head ->next == NULL) return new TreeNode(head->val);

        auto pre = head;

        auto slow = pre->next;

        auto fast = slow->next;

        while(fast != NULL && fast->next != NULL) {

            fast = fast->next->next;

            slow = slow->next;

            pre = pre->next;

        }

        auto next_right = slow->next; 

        auto root = new TreeNode(slow->val);

        pre->next = nullptr;

         

        root->left = sortedListToBST(head);

        root->right = sortedListToBST(next_right);

        return root;

    }

};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章