Convert Sorted List to Binary Search TreeOct
3 '12
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
uncompleted
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
if( head==null ) return null;
ListNode p = head;
while(p.next!=null) {
p = p.next;
}
return bstRec(head, p);
}
private TreeNode bstRec(ListNode low, ListNode high) {
if(low == high) return null;
ListNode p=low, q=low;
while(q!=high) {
if( q.next == null ) break;
q = q.next.next;
p = p.next;
}
TreeNode head = new TreeNode( p.next.val );
head.left = bstRec(low, p);
if(p.next!=null){
bstRec(p.next,high);
}
return head;
}
}