Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
´Ó¸ø¶¨µÄÓÐÐòÁ´±íÉú³Éƽºâ¶þ²æÊ÷¡£
½âÌâ˼·£º×îÈÝÒ×Ïëµ½µÄ¾ÍÊÇÀûÓÃÊý×éÉú³É¶þ²æÊ÷µÄ·½·¨£¬ÕÒµ½Öмä½Úµã×÷Ϊ¶þ²æÊ÷µÄroot½Úµã£¬È»ºó·Ö±ð¶Ô×óÓÒÁ´±íµÝ¹éµ÷Ó÷ֱðÉú³É×ó×ÓÊ÷ºÍÓÒ×ÓÊ÷¡£Ê±¼ä¸´ÔÓ¶ÈO(N*lgN)
AC´úÂ룺
public class Solution {
ListNode getLeftNodeFromList(ListNode head) {
ListNode next = head;
ListNode current = head;
ListNode pre = head;
while(next!=null) {
next = next.next;
if(next==null) {
break;
}
next = next.next;
if(next==null) {
break;
}
pre = head;
head = head.next;
}
return pre;
}
public TreeNode sortedListToBST(ListNode head) {
if(head==null) {
return null;
}
if(head.next==null) {
return new TreeNode(head.val);
}
ListNode left = getLeftNodeFromList(head);
ListNode mid = left.next;
TreeNode root = new TreeNode(mid.val);
left.next = null;
root.left = sortedListToBST(head);
root.right = sortedListToBST(mid.next);
return root;
}
}
|