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

原题网址:https://leetcode.cn/problems/convert-sorted-list-to-binary-search-tree/

有序链表转为高度平衡的二叉搜索树。

有序,高度平衡,所以就从链表的中间分,形成树,用到了归并思想

    // 还得是高度平衡的二叉搜索树。座椅必须以链表的中点分开。
    // 由于是有序的,所以遍历链表,逐个添加后依旧是链表结构,不行。

    public TreeNode sortedListToBST(ListNode head) {
        return mergeListToBST(head,null);

    }
    // 注意这里的区间是左闭右开
    private TreeNode mergeListToBST(ListNode head, ListNode tail) {
        // 遍历完了链表,因为是左闭右开的区间
        if(head == tail) {
            return null;
        }
        // 这个是只有一个元素了
        if(head.next == tail) {
            return new TreeNode(head.val);
        }

        ListNode midNode = getMidNode(head,tail);
        TreeNode root = new TreeNode(midNode.val);
        root.left  = mergeListToBST(head,midNode);
        root.right = mergeListToBST(midNode.next,tail);
        return root;
    }

    private ListNode getMidNode(ListNode head, ListNode tail) {
        ListNode fast = head;
        ListNode slow = head;
        while(fast != tail && fast.next != tail) {
            fast= fast.next.next;
            slow= slow.next;
        }
        return slow;

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值