113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

经典的DFS题目,
重点就是dfs函数中的cur和res参数,利用cur不断保存当前路径上的参数,利用res保存符合题目的数组

class Solution(object):
    def pathSum(self, root, sum):
        if not root:
            return []
        res = []
        self.dfs(root, sum, [], res)
        return res
    
    def dfs(self, root, sum, cur, res):
        if not root.left and not root.right and sum == root.val:
            cur.append(root.val)
            res.append(cur)
        if root.left:
            self.dfs(root.left, sum-root.val, cur+[root.val], res)
        if root.right:
            self.dfs(root.right, sum-root.val, cur+[root.val], res)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容