有序链表构造平衡二叉树。
递归的思路,感觉比较直接一些。
ListNode cur;
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
int size = 0;
ListNode t = head;
cur = head;
while (t != null) {
size++;
t = t.next;
}
return construct(1, size);
}
private TreeNode construct(int l, int r) {
if (l > r) return null;
int mid = (l + r) / 2;
TreeNode left = construct(l, mid - 1);
TreeNode root = new TreeNode(cur.val);
root.left = left;
cur = cur.next;
root.right = construct(mid + 1, r);
return root;
}
非递归不会。。
看题解还有快慢链表的思路