资讯专栏INFORMATION COLUMN

[LeetCode] 109. Convert Sorted List to Binary Sear

dongfangyiyu / 2080人阅读

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 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
Solution
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        return helper(head, null);
    }
    private TreeNode helper(ListNode head, ListNode tail) {
        if (head == tail) return null;
        ListNode fast = head, slow = head;
        while (fast != tail && fast.next != tail) {
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.left = helper(head, slow);
        root.right = helper(slow.next, tail);
        return root;
    }
}

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

转载请注明本文地址:https://www.ucloud.cn/yun/72186.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] 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
  • 109. Converted 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. 答案: /** * Definition for singly-linked list. * p...

    plokmju88 评论0 收藏0
  • [LeetCode] Convert Sorted Array to Binary Search T

    摘要:思路根据的性质,问题转化为找一个里的中位数,用一个函数,一路找中点,再通过前序遍历的方法把起来代码 Convert Sorted Array to Binary Search Tree With Minimal Height Given a sorted (increasing order) array, Convert it to create a binarytree with m...

    willin 评论0 收藏0
  • [Leetcode-Tree] Convert Sorted Array to Binary Sea

    摘要:解题思路平衡二叉树,其实就是数组中间的数作为根,利用递归实现左子树和右子树的构造。 Convert Sorted Array to Binary Search TreeGiven an array where elements are sorted in ascending order, convert it to a height balanced BST. 1.解题思路平衡二叉树,...

    songze 评论0 收藏0

发表评论

0条评论

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