/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private ListNode current;
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
current = head;
int size = getListSize(head);
return sortedListToBSTHelper(size);
}
private int getListSize(ListNode head) {
int size = 0;
while (head != null) {
size++;
head = head.next;
}
return size;
}
private TreeNode sortedListToBSTHelper(int size) {
if (size <= 0) {
return null;
}
TreeNode left = sortedListToBSTHelper(size / 2);
TreeNode root = new TreeNode(current.val);
current = current.next;
TreeNode right = sortedListToBSTHelper(size - size / 2 - 1);
root.left = left;
root.right = right;
return root;
}
}