Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
代码语言:javascript复制不能将linked list转换成arraylist,会超时。思路:快慢指针。
ListNode cutAtMid(ListNode head) {
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
ListNode pslow = head;
while (fast != null && fast.next != null) {
pslow = slow;
slow = slow.next;
fast = fast.next.next;
}
pslow.next = null;
return slow;
}
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return new TreeNode(head.val);
}
ListNode mid = cutAtMid(head);
TreeNode root = new TreeNode(mid.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(mid.next);
return root;
}