Leetcode 题目解析之 Convert Sorted List to Binary Search Tree

2022-01-14 11:33:25 浏览数 (1)

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

不能将linked list转换成arraylist,会超时。思路:快慢指针。

代码语言:javascript复制
    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;
    }

0 人点赞