资讯专栏INFORMATION COLUMN

109. Converted Sorted List to Binary Search Tree

plokmju88 / 2934人阅读

摘要:题目答案这里是不能等于也省去了把从中间分隔时,需要添加的麻烦

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

答案:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode BST(ListNode head, ListNode tail) {
        ListNode slow = head, fast = head;
        if (head == tail) return null;
        
        //这里是fast不能等于tail,也省去了把listnode从中间分隔时,需要添加null的麻烦!
        while (fast != tail && fast.next != tail) {
            slow = slow.next;
            fast = fast.next.next;
        }
        
        TreeNode root = new TreeNode(slow.val);
        root.left = BST(head, slow);
        root.right = BST(slow.next, tail);
        return root;
    }
    
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        return BST(head, null);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64921.html

相关文章

  • leetcode109. Convert Sorted List to Binary Search

    摘要:题目要求给一个按照递增顺序排列的链表。将该链表转化为平衡二叉树。思路和代码在这里需要注意的是,因为提供的数据结构为链表,所以我们必须顺序遍历才能知道该链表的长度以及该链表的中间位置。并依次递归左子节点和右子节点。 题目要求 Given a singly linked list where elements are sorted in ascending order, convert i...

    高胜山 评论0 收藏0
  • [LeetCode] 109. Convert Sorted List to Binary Sear

    Problem 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 whi...

    dongfangyiyu 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • leetcode部分题目答案之JavaScript版

    摘要:自己没事刷的一些的题目,若有更好的解法,希望能够一起探讨项目地址 自己没事刷的一些LeetCode的题目,若有更好的解法,希望能够一起探讨 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...

    alphahans 评论0 收藏0
  • [Leetcode] Convert Sorted Array/List to Binary Sea

    摘要:我们可以用和两个值来限定子树在链表中的位置,通过递归的方式,深入找到最左边,然后开始顺序遍历链表链表当前节点作为全局变量,这样无论递归在哪我们都能拿到,同时建树。代码先递归的计算左子树创造根节点最后递归的计算右子树 Convert Sorted List to Binary Search Tree Given a singly linked list where elements ar...

    wpw 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<