程式語言 - LeetCode - C++ - 109. Convert Sorted List to Binary Search Tree



參考資訊:
https://www.cnblogs.com/grandyang/p/4295618.html

題目:


解答:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if (!head) {
            return nullptr;
        }

        if (!head->next) {
            return new TreeNode(head->val);
        }

        ListNode *pre = nullptr;
        ListNode *slow = head;
        ListNode *fast = head;

        while (fast && fast->next) {
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }

        if (pre) {
            pre->next = nullptr;
        }

        TreeNode *t = new TreeNode(slow->val);
        t->left = sortedListToBST(head == slow ? nullptr : head);
        t->right = sortedListToBST(slow->next);

        return t;
    }
};