Given a singly linked list where elements are sorted in ascending order, convert it
to a height balanced BST.
从下往上,从左往右构造二叉树。
static ListNode h;
public TreeNode sortedListToBST(ListNode head) {
h = head;
int len = 0;
ListNode p = head;
while (p != null) {
len++;
p = p.next;
}
return sortedListToBST(len);
}
public TreeNode sortedListToBST(int size) {
if (size<=0)
return null;
TreeNode left = sortedListToBST(size/2);
TreeNode root = new TreeNode(h.val);
h = h.next;
TreeNode right = sortedListToBST(size-1-size/2);
root.left = left;
root.right = right;
return root;
}