LeetCode-Python-113. 路径总和 II

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

思路:

DFS 找到每一条从根节点到叶节点的路径,然后判断路径之和是否等于需要的TARGET。

卡了五分钟,因为把路径添加到res之后直接return了,而没有做POP的回溯操作。

# 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, s):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        res = list()
        
        def dfs(node, tmp):
            if not node:
                return 
            
            tmp.append(node.val) 
            if not node.left and not node.right and sum(tmp) == s:
                res.append(tmp[:])#找到一条OK的路了
            
            dfs(node.left, tmp)
            dfs(node.right, tmp)
            tmp.pop()
            
        dfs(root, list())        
        return res

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/89046384