leetcode109 - Convert Sorted List to Binary Search Tree - medium

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

 

Example 1:

Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [0]
Output: [0]

Example 4:

Input: head = [1,3]
Output: [3,1]

 

Constraints:

  • The number of nodes in head is in the range [0, 2 * 104].
  • -10^5 <= Node.val <= 10^5

因为本身排序好了,所以不用担心BST的条件,为了做到balanced,取中点作为root就好。快慢指针找中点,同时keep一个prev指针指向slow的前一个,这样方便断开前半部分和mid。左半边就是left subtree右半边就是right subtree,然后递归下去。要是prev指向空了,也就是此时ll里只有一个node的时候,就不用call左右了。

 

实现:Time O(nlogn) 第一次n/2, 第二次2*n/4, 第三次4*n/8,...总共logn次 Space O(logn)

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

 

posted @ 2020-11-01 11:50  little_veggie  阅读(100)  评论(0)    收藏  举报