Convert Sorted List to Binary Search Tree
Total Accepted: 5229 Total Submissions: 19480
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
第一种用二分,很容易想到,复杂度 O(nlogn).
第二种,直接 build from bottom to top, 使用头尾两个index 来判断节点的位置。
// O(ologn)
public static TreeNode sortedListToBST(ListNode head){
if(head == null) return null;
if(head.next == null) return new TreeNode(head.val);
ListNode slow = head, fast = head.next.next;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
}
ListNode mid = slow.next;
slow.next = null;
TreeNode root = new TreeNode(mid.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(mid.next);
return root;
}
//O(n)
static ListNode gHead;
public static TreeNode sortedListToBST2(ListNode head){
if(head == null) return null;
gHead = head;
int len = 0;
while(head!=null){
len++;
head = head.next;
}
return buildBST(0,len-1);
}
private static TreeNode buildBST(int start, int end){
if(start > end) return null;
int mid = (start+end)/2;
TreeNode left = buildBST(start,mid-1);
TreeNode root = new TreeNode(gHead.val);
gHead = gHead.next;
TreeNode right = buildBST(mid+1,end);
root.left = left; root.right = right;
return root;
}