Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
The idea is to find the middle list node and make it root node in the binary tree, then separate the list into left and right and recursively find the middle list node.
//find the previous node pointers to middle
private ListNode getLeftPointer(ListNode head) {
ListNode previous = head;
ListNode slow = head;
ListNode fast = head;
while (fast!=null&&fast.next!=null) {
previous = slow;
slow = slow.next;
fast = fast.next.next;
}
return previous;
}
public TreeNode sortedListToBST(ListNode head) {
if (head==null) {
return null;
}
if (head.next==null) {
return new TreeNode(head.val);
}
ListNode left = getLeftPointer(head);
ListNode middle = left.next;
TreeNode root = new TreeNode(middle.val);
left.next = null;
root.left = sortedListToBST1(head);
root.right = sortedListToBST1(middle.next);
return root;
}