首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Leetcode 题目解析之 Convert Sorted List to Binary Search Tree

Leetcode 题目解析之 Convert Sorted List to Binary Search Tree

原创
作者头像
ruochen
发布2022-01-14 11:33:25
发布2022-01-14 11:33:25
1.2K0
举报

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

不能将linked list转换成arraylist,会超时。思路:快慢指针。

代码语言:javascript
复制
    ListNode cutAtMid(ListNode head) {

        if (head == null) {
            return null;
        }

        ListNode fast = head;
        ListNode slow = head;
        ListNode pslow = head;

        while (fast != null && fast.next != null) {
            pslow = slow;
            slow = slow.next;
            fast = fast.next.next;
        }

        pslow.next = null;
        return slow;
    }

    public TreeNode sortedListToBST(ListNode head) {

        if (head == null) {
            return null;
        }

        if (head.next == null) {
            return new TreeNode(head.val);
        }

        ListNode mid = cutAtMid(head);

        TreeNode root = new TreeNode(mid.val);
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(mid.next);

        return root;
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档