[leetcode] @python 113. Path Sum II

题目链接

https://leetcode.com/problems/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.

For example: Given the below binary tree and sum = 22, return

题目大意

上一题的扩展版,返回满足所有符合条件的路径

解题思路

使用dfs遍历

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        def dfs(root, cursum, valuelist):
            if root.left == None and root.right == None:
                if cursum == sum:
                    ans.append(valuelist)
            if root.left:
                dfs(root.left, cursum + root.left.val, valuelist + [root.left.val])
            if root.right:
                dfs(root.right, cursum + root.right.val, valuelist + [root.right.val])

        ans = []
        if root == None:
            return []
        dfs(root, root.val, [root.val])
        return ans   
原文地址:https://www.cnblogs.com/slurm/p/5272465.html