class Solution {
public:
    TreeNode *sortedListToBST(ListNode* head) {
        if (!head) return NULL;
        if (!head->next) return new TreeNode(head->val);
        ListNode *slow = head, *fast = head, *last = slow;
        while (fast->next && fast->next->next) {
            last = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        fast = slow->next;
        last->next = NULL;
        TreeNode *cur = new TreeNode(slow->val);
        if (head != slow) cur->left = sortedListToBST(head);
        cur->right = sortedListToBST(fast);
        return cur;
    }
};

相关文章:

  • 2021-11-11
  • 2021-10-10
  • 2021-10-24
  • 2021-06-20
  • 2022-01-12
  • 2022-01-03
  • 2021-06-25
  • 2021-11-17
猜你喜欢
  • 2021-10-18
  • 2021-12-27
  • 2022-01-16
  • 2021-05-27
相关资源
相似解决方案