美文网首页
2019-08-22 剑指 二叉树中和为某一值的路径

2019-08-22 剑指 二叉树中和为某一值的路径

作者: mztkenan | 来源:发表于2019-08-22 22:56 被阅读0次

很简单的DFS,但是不知道为何sum嵌套函数找不到变量?

class Solution:
    # 返回二维列表,内部每个列表表示找到的路径
    def FindPath(self, root:TreeNode, expectNumber:int):
        res,path=[],[]
        def dfs(root,good):
            if not root:return None
            good+=root.val
            path.append(root)
            if not root.left and not root.right and good==expectNumber:res.append(path+[])
            if root.left:dfs(root.left,good)
            if root.right:dfs(root.right,good)
            good-=root.val
            path.pop()
        dfs(root,0)
        return res

        # def FindPath(self, root, expectNumber):
        #     def dfs(root):
        #         sum += root.val
        #         path.append(root)
        #         if not root.left and not root.right and sum == expectNumber: res.append(path + [])
        #         if root.left: dfs(root.left)
        #         if root.right: dfs(root.right)
        #         sum -= root.val
        #         path.pop()
        #
        #     res, path, sum = [], [], 0
        #     dfs(root)
        #     # return res

相关文章

网友评论

      本文标题:2019-08-22 剑指 二叉树中和为某一值的路径

      本文链接:https://www.haomeiwen.com/subject/dqoosctx.html