LeetCode 109. 有序链表转换二叉搜索树

//方法1,将有序链表的元素全部保存到一个List,就将此问题转化为了108题
//方法2,直接找链表的中心点,(876题),剩下的就和108的思想一样了,本人用方法二解题
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        //边界处理,链表为空时,返回null
        if(head == null) return null;
        //只有一个元素,构建的树只有一个根节点
        if(head.next == null) return new TreeNode(head.val);
        //剩下的情况应该找链表的中心点了,这里用快慢指针法,快指针走2步,慢指针走一步,
        //但需注意的是 链表要从中心点断开,以便遍历左子树,所以需要将中心点的前一个节点的指针指向null
        
        ListNode fast = head,low = head;
        //定义pre指针 保存中心点的前一个节点
        ListNode pre = null;
        while(fast != null && fast.next != null){
            pre = low;
            low = low.next;
            fast = fast.next.next;
        }
        //遍历完链表后,三个节点到了相应的位置,此时断开链表
        pre.next = null;

        //以链表的中心点为根节点构建二叉搜索树
        TreeNode root = new TreeNode(low.val);
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(low.next);
        //返回构建的二叉搜索树
        return root;

    }
}
原文地址:https://www.cnblogs.com/peanut-zh/p/13887834.html