V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2020-06-19 02:39:56 +08:00 · 1717 次点击
    这是一个创建于 1400 天前的主题,其中的信息可能已经有所发展或是发生改变。

    测试用例[-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 条回复    2020-06-19 14:43:02 +08:00
    Xs0ul
        1
    Xs0ul  
       2020-06-19 02:48:05 +08:00
    我试了你的也可以 ac 的,这个测试用例上也是对的,如果你在做的是 108 的话

    不如重启试试
    noqwerty
        2
    noqwerty  
       2020-06-19 02:50:52 +08:00
    你这一模一样的代码怎么可能跑不通,清一下缓存试试?
    UN2758
        3
    UN2758  
    OP
       2020-06-19 14:43:02 +08:00
    应该是我把前面 treenode 定义反注释了的缘故
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3617 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:31 · PVG 18:31 · LAX 03:31 · JFK 06:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.