原题链接:https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
方法I: Divde-and-Conquer, Top-down (同5.3.4 Convert Sorted Array to BST)
Time: O(n) + O(nlogn) = O(nlogn), Space: O(logn)
"Look for the middle element in the list, set it as the root and then recursively build up left and right subtrees. In each recursive call, you would have to traverse half of the list’s length to find the middle element. The run time complexity is clearly O(N lg N), where N is the total number of elements in the list. This is because each level of recursive call requires a total of N/2 traversal steps in the list, and there are a total of lg N number of levels (ie, the height of the balanced tree). (Ref: http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
//calculate list length
int len = 0;
ListNode cur = head;
while(cur != null){
cur = cur.next;
len ++;
}
return sortedListToBST(head, 0, len - 1);
}
private TreeNode sortedListToBST(ListNode head, int low, int high){
if(low > high) return null;
//find the mid node
int mid = (low + high)/2;
int count = mid;
ListNode midNode = head;
while(count > low){
midNode = midNode.next;
count --;
}
TreeNode root = new TreeNode(midNode.val);
root.left = sortedListToBST(head, low, mid - 1);
root.right = sortedListToBST(midNode.next, mid+1, high);
return root;
}
}
方法II: Bottom-up. Time: O(n), Space: O(logn). 不完全理解它为什么正确。to understand
public class Solution {
//bottom-up approach
public TreeNode sortedListToBST(ListNode head) {
//this part is the same as top-down
int len = 0;
ListNode cur = head;
while(cur!=null){
cur = cur.next;
len++;
}
return sortedListToBST(head, 0, len - 1);
}
private TreeNode sortedListToBST(ListNode head, int low, int high){
if(low > high) return null;
//find the mid node
int mid = (low + high)/2;
TreeNode leftNode = sortedListToBST(head, low, mid - 1);
TreeNode root = new TreeNode(head.val);
root.left = leftNode;
if(head.next != null){
head.val = head.next.val;
head.next = head.next.next;
}
root.right = sortedListToBST(head, mid+1, high);
return root;
}
}