【力扣】109. 有序链表转换二叉搜索树

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

0
/
-3 9
/ /
-10 5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree

 时间复杂度:O(n * log n),其中 n 是链表的长度。空间复杂度:O(n * log n)

public TreeNode sortedListToBST(ListNode head) {
        //这个题最重要的就是找到中间点
        if(head == null) return null;
        else if(head.next == null) return new TreeNode(head.val);
        ListNode pre = head; //设置该节点,目的是什么呢?目的是做链表的分离
        ListNode slow = head.next; // 设置两个节点,一个快的节点,一个慢的节点,快的节点一次走两个格,慢的节点一次走一个格,则当快的节点到头时,慢节点的位置就是中间
        ListNode fast = head.next.next;
        while( fast!= null && fast.next != null){
            pre = pre.next; //这里是为了找到中间左边的节点
            fast = fast.next.next;
            slow = slow.next;//这里是为了到最后
        }
        //找到中间点slow
        pre.next=null; //将链表的中间节点同下一个分离
        TreeNode root = new TreeNode(slow.val);
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(slow.next); 
        return root;
    }
一个入行不久的Java开发,越学习越感觉知识太多,自身了解太少,只能不断追寻
原文地址:https://www.cnblogs.com/fengtingxin/p/13524011.html