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: []
解答
方法一
Runtime: 80 ms, faster than 92.71% of JavaScript online submissions for Convert Sorted List to Binary Search Tree.
Memory Usage: 47.2 MB, less than 88.15% of JavaScript online submissions for Convert Sorted List to Binary Search Tree.
Time Complexity: O(NlogN)
分拆一個長度為 N 的 linked list 花費時間為 N / 2 (找到 middle 的時間),總共會分拆 logN 次,所以全部加起來會是 O(NlogN)
Space Complexity: O(logN)
O(N) for skewed tree,O(logN) for height balanced tree
方法二
先將 linked list 轉為一般的 array,再套用 108. 題的解法,如此的話 Time Complexity 可以改進到 O(N),但 Space Complexity 會變為 O(N)
Runtime: 95 ms, faster than 71.25% of JavaScript online submissions for Convert Sorted List to Binary Search Tree.
Memory Usage: 48 MB, less than 42.81% of JavaScript online submissions for Convert Sorted List to Binary Search Tree.