LeetCode:109. Convert Sorted List to Binary Search Tree

题目要求大体如下:

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

  0
 / \
-3   9
/   /
-10  5

大体的要求就是给你一个升序的链表,构造一个平衡的二叉搜索树。

一.我的解法

因为是要构建平衡的二叉搜索树,所以肯定是要从升序链表的中点开始构造。所以首先要找到链表的中点,利用两个指针遍历链表,慢指针就是中点。这个时候边界问题要注意一下,我在这里N/A了好几次。
时间复杂度是O(nlogn)。

class Solution{
    public TreeNode sortedListToBST(ListNode head){
        if(head==null) return null;
        return helper(head,null);
    }
    public TreeNode helper(ListNode start,ListNode end){
        if(start==end||start==null) return null;
        if(start.next==end) return new TreeNode(start.val);
        ListNode fast=start;
        ListNode slow=start;
        while(fast!=end&&fast.next!=end)
        {
            fast=fast.next.next;
            slow=slow.next;
        }
        TreeNode root=new TreeNode(slow.val);
        root.left=helper(start,slow);
        root.right=helper(slow.next,end);
        return root;
    }
}

二.扩展

其实一开始的时候,我想模仿二分查找法的样子,先利用一个指针遍历链表,并记录长度。然后,计算出中点。但是,思路总是不对,所以想了一会后就先放弃了这个解法。然后等上面这个解法AC了之后,我又准备重新拾起这个想法,参考了别人的解法之后,发现这个解法其实可以通过中序遍历构造二叉树。
时间复杂度应该是O(NlogN)
这个是原参考地址:
https://discuss.leetcode.com/topic/8141/share-my-o-1-space-and-o-n-time-java-code

class Solution {
    ListNode node;
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) return null;
        ListNode point=head;
        int length=0;
        node=head;
        while(point!=null)
        {
            point=point.next;
            length++;
        }
        return helper(0,length-1);
    }
    public TreeNode helper(int low,int high){
        if(low>high) return null;
        int mid=low+(high-low)/2;
        TreeNode left=helper(low,mid-1);
        TreeNode root=new TreeNode(node.val);
        root.left=left;
        node=node.next;
        TreeNode right=helper(mid+1,high);
        root.right=right;
        return root;
    }
}

如果有什么错误或者可以改进的地方,请积极指出,我会认真改进的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值