zoukankan      html  css  js  c++  java
  • LeetCode 109. 有序链表转换二叉搜索树

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

    Difficulty: 中等

    给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

    本题中,一个高度平衡二叉树是指一个二叉树_每个节点 _的左右两个子树的高度差的绝对值不超过 1。

    示例:

    给定的有序链表: [-10, -3, 0, 5, 9],
    
    一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
    
          0
         / 
       -3   9
       /   /
     -10  5
    

    Solution

    Language: 全部题目

    跟有序数组转换二叉搜索树一样,首先把有序链表转换成为数组就行了,第一次提交的时候错误,因为当链表为None的时候返回了空列表,跟预期的返回数据格式不一致。

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def sortedListToBST(self, head: ListNode) -> TreeNode:
            if not head: return None
            nums = []
            while head:
                nums.append(head.val)
                head = head.next
            def buildHelper(start, end):
                if start > end: return None
                mid = (end + start) // 2
                root = TreeNode(nums[mid])
                root.left = buildHelper(start, mid-1)
                root.right = buildHelper(mid+1, end)
                return root
    ​
            n = len(nums)
            return buildHelper(0, n-1)
    
  • 相关阅读:
    【BZOJ3489】A simple rmq problem【kd树】
    【BZOJ2716】天使玩偶【kd树】
    Codeforces Round #520 (Div. 2)
    Codeforces Round #521 (Div. 3)
    Educational Codeforces Round 54
    【hdu3507】Print Article 【斜率优化dp】
    【HDU5992】Finding Hotels 【KD树】
    【hdu4347】The Closest M Points 【KD树模板】
    【BZOJ2806】Cheat 【广义后缀自动机+单调队列优化dp+二分】
    SDSC2018 Day1
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14042006.html
Copyright © 2011-2022 走看看