0
点赞
收藏
分享

微信扫一扫

【剑指offer】034.二叉树中和为某一值的路径

绣文字 2022-04-19 阅读 71
leetcode

题目

【剑指offer】034.二叉树中和为某一值的路径

解法

DFS。但是这里要注意python的一些特性。
python传参传对象,可变对象可变,不可变对象不可变

class Solution:
    def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
        res, cur = [], []
        def dfs(root, tar):
            if not root: return 
            cur.append(root.val)
            if root.left is None and root.right is None and root.val==tar:
                res.append(list(cur)) # 这个域里,要用list()将cur转成值,不然,cur是一个可变对象,后面cur变化,res也会变
            else:
                dfs(root.left, tar-root.val)
                dfs(root.right, tar-root.val)
            cur.pop(-1)
        dfs(root, target)
        return res
举报

相关推荐

0 条评论