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

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

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

执行用时:1 ms, 在所有 Java 提交中击败了66.07%的用户
内存消耗:41.5 MB, 在所有 Java 提交中击败了5.15%的用户
二分法/分治
有序链表相当于二叉搜索树的中序遍历,采用二分法不断获取其每一段的中间节点作为子树根节点最终还原二叉搜索树

/*时间复杂度: O(NlogN)*/
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) {
            return null;
        }
        else if(head.next==null) {
            return new TreeNode(head.val);
        }

        //获取链表的长度O(N)
        int len = 0;
        ListNode tmp = head;
        while(tmp!=null) {
            len++;
            tmp = tmp.next;
        }

        TreeNode root = sortedListToBST(head, len);

        return root;
    }

    public TreeNode sortedListToBST(ListNode head, int len) {
        if(len==1) {
            return new TreeNode(head.val);
        }
        else if(len==0) {
            return null;
        }

        ListNode root = head;
        //找到根节点(根据传入的长度,遍历到中间位置)
        for(int i=0; i<len/2; i++) {
            root = root.next;
        }
        TreeNode Root = new TreeNode(root.val);
        //左右子树根节点
        TreeNode leftRoot = sortedListToBST(head, len/2);
        TreeNode rightRoot = sortedListToBST(root.next, len - (len/2+1));
        //拼接
        Root.left = leftRoot;
        Root.right = rightRoot;

        return Root;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13521640.html