1. 程式人生 > >LeetCode - Convert Sorted List to Binary Search Tree

LeetCode - Convert Sorted List to Binary Search Tree

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if(!head) return nullptr;
        if(!head->next) return new TreeNode(head->val);
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* last = slow;
        while(fast->next && fast->next->next){
            last = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        fast = slow->next;       //must before the next line since last and slow may be the same node
        last->next = NULL;
        TreeNode* cur = new TreeNode(slow->val);
        if(head!=slow) cur->left = sortedListToBST(head);
        cur->right =  sortedListToBST(fast);
        return cur;
        
    }
};

基本迴圈(>=3 nodes):

1. 中間數為root

2. 將原資料分成兩段:前半段為left substree, 後半段為right subtree

沒有node、一個node情況被開頭的兩個if statement handle

兩個nodes的時候,slow=last=head 成為root, fast=slow->next成為right