账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    关于二叉树的一道简单算法题,结果很诡异(python)
    16
    0

    lintcode原题:
    二叉树的路径和
    给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。
    一个有效的路径,指的是从根节点到叶节点的路径。
    我的解答

    """
    Definition of TreeNode:
    class TreeNode:
        def __init__(self, val):
            self.val = val
            self.left, self.right = None, None
    """
    
    
    class Solution:
        """
        @param: root: the root of binary tree
        @param: target: An integer
        @return: all valid paths
        """
        def binaryTreePathSum(self, root, target):
            # write your code here
            result=[]
            path=[]
            self.dfs(root,path,result,target)
            return result
            
            
            
        def dfs(self,root,path,result,target):
            if root is None:
                return
            path.append(root.val)
            if  root.left is None and  root.right is None and sum(path)==target:
                result.append(path)
            if root.left:
                self.dfs(root.left,path,result,target)
            if root.right:
                self.dfs(root.right,path,result,target)
            path.pop()
                

    结果总是错误
    输入
    {1,2,4,2,3}
    5
    输出
    [[],[]]
    期望答案
    [[1,2,2],[1,4]]

    我实在想不通为什么答案是空,后来我意识到可能是传参数的问题,改成如下代码:

    if  root.left is None and  root.right is None and sum(path)==target:
                result.append(path+[])

    这里只改了中间那一行,将path改为path+[],居然华丽丽的成功了,实在是想不通为什么,有人指点一二吗?谢了!

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 小沙橘 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部