• 108. Convert Sorted Array to Binary Search Tree


    题目来源:

    https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/submissions/

    自我感觉难度/真实难度:easy/easy
     
    题意:

     把一个list转化为平衡树

    分析:
     
    自己的代码:
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def sortedArrayToBST(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            """
            index=len(nums)
            if index==0:
                return None
            if index==1:
                return TreeNode(nums[0])
            
            cur=TreeNode(nums[index//2])
            cur.left =self.sortedArrayToBST(nums[:index//2])
            cur.right=self.sortedArrayToBST(nums[index//2+1:])
            return cur
            
    代码效率/结果:

    Runtime: 104 ms, faster than 88.84% of Python3 online submissions forConvert Sorted Array to Binary Search Tree.

     解题思路还是有的,但是总是一些细节出问题:1.返回值,一定要各处都符合需要的类型,这是是TreeNode    2.一个list需要分割成两半的时候,不仅是需要考虑list长度为0时,还有list长度为1的时候   3.看清楚list中index的取值,取值是不会拿掉原来数组中的值得

    优秀代码:
    class Solution:
        def sortedArrayToBST(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            """
            return self.subSortedArrayToBST(nums,0,len(nums)-1)
            
        def subSortedArrayToBST(self,l,i,j):
            if l == [] :
                return []
            BST = TreeNode(l[(i+j+1)//2])
            if i <= (i+j+1)//2-1:
                BST.left = self.subSortedArrayToBST(l,i,(i+j+1)//2-1)
            if j >= (i+j+1)//2+1:
                BST.right = self.subSortedArrayToBST(l,(i+j+1)//2+1,j)
            return BST
    代码效率/结果:

    Runtime: 108 ms, faster than 71.50% of Python3 online submissions forConvert Sorted Array to Binary Search Tree.

    完美的告诉你,应该如何去改写答案给的函数,使用自己定义的函数

     
    自己优化后的代码:
     
    反思改进策略:

    1.提交之前要检查变量名称是否一致

    2.对list分割取一般时,index要考虑等于0和1的情况

  • 相关阅读:
    LeetCode OJ:Divide Two Integers(两数相除)
    LeetCode OJ:Sqrt(x)(平方根)
    LeetCode OJ:Excel Sheet Column Number(表格列数)
    LeetCode OJ:Compare Version Numbers(比较版本字符串)
    LeetCode OJ:Valid Parentheses(有效括号)
    LeetCode OJ:Longest Common Prefix(最长公共前缀)
    LeetCode OJ:Linked List Cycle II(循环链表II)
    LeetCode OJ:Permutations II(排列II)
    LeetCode OJ:Permutations(排列)
    MongoDB复制二:复制集的管理
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10261621.html
Copyright © 2020-2023  润新知