推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
UN2758
V2EX  ›  Python

求解:两种递归方式的差异?

  •  
  •   UN2758 · Jun 19, 2020 · 2542 views
    This topic created in 2297 days ago, the information mentioned may be changed or developed.

    测试用例[-10,-3,0,5,9],前面是我的写法,返回结果是[]

    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    class Solution:
        def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
            
            if not nums:
                return None
            else:
                middle = len(nums)//2
                root =TreeNode(nums[middle])
                root.left=self.sortedArrayToBST(nums[0:middle])
                root.right=self.sortedArrayToBST(nums[middle+1:len(nums)])
    
            return root
    

    后面是路人的写法,可以 AC

    class Solution:
        def sortedArrayToBST(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            """
            if not nums:
                return None
            else:
                mid=len(nums)//2
                tn=TreeNode(nums[mid])
                nums1=nums[0:mid]
                nums2=nums[mid+1:len(nums)]
                tn.left=self.sortedArrayToBST(nums1)
                tn.right=self.sortedArrayToBST(nums2)
            return tn
    

    感觉很奇怪啊,不知道为什么

    3 replies  •  2020-06-19 14:43:02 +08:00
    Xs0ul
        1
    Xs0ul  
       Jun 19, 2020
    我试了你的也可以 ac 的,这个测试用例上也是对的,如果你在做的是 108 的话

    不如重启试试
    noqwerty
        2
    noqwerty  
       Jun 19, 2020
    你这一模一样的代码怎么可能跑不通,清一下缓存试试?
    UN2758
        3
    UN2758  
    OP
       Jun 19, 2020
    应该是我把前面 treenode 定义反注释了的缘故
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2204 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 05:47 · PVG 13:47 · LAX 22:47 · JFK 01:47
    ♥ Do have faith in what you're doing.