LeetCode每日一题:通过有序链表建立二叉搜索树

问题描述

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

问题分析

这题让我们通过一个有序的链表建立二叉搜索树BST,注意到BST的中序排列必定是有序的,所以我们通过快慢指针寻找链表的中点再建立树就可以了。

代码实现

public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return new TreeNode(head.val);
        ListNode mid = head;
        ListNode end = head;
        ListNode preMid = null;
        while (end != null && end.next != null) {
            preMid = mid;
            mid = mid.next;
            end = end.next.next;//快慢指针找中点
        }
        TreeNode root = new TreeNode(mid.val);
        preMid.next = null;
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(mid.next);
        return root;
    }

你可能感兴趣的:(LeetCode每日一题:通过有序链表建立二叉搜索树)