leetcode109 - Convert Sorted List to Binary Search Tree - medium
阿新 • • 發佈:2020-11-01
Given thehead
of a singly linked list where elements aresorted 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 ofeverynode 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; } };