思路:和108题类似,链表需要通过双指针寻找中间节点。
class Solution { public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; if (head.next == null) return new TreeNode(head.val); ListNode fast = head, slow = head, pre = null; while (fast != null && fast.next != null) { pre = slow; fast = fast.next.next; slow = slow.next; } pre.next = null; TreeNode root = new TreeNode(slow.val); root.left = sortedListToBST(head); root.right = sortedListToBST(slow.next); return root; } }