113. 路径总和 II

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

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

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

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回:

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

思路:

  • 与257二叉树的所有路径类似,先序遍历二叉树
  • 注意利用列表存储遍历的路径时,递归传入参数时需要深拷贝(python)
  • 当遍历到叶子节点时,将遍历的路径存入结果列表中,最后检查结果列表中哪些满足条件
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

import copy

class Solution(object):
    def pathSum(self, root, sum_value):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        path_list, result = [], []

        self.helper(root, path_list, result)

        return [path for path in result if sum(path) == sum_value]

        
    def helper(self, root, path_list, result):
        if not root:
            return 
        
        path_list.append(root.val)

        if root.left:
            self.helper(root.left, copy.deepcopy(path_list), result)
        
        if root.right:
            self.helper(root.right, copy.deepcopy(path_list), result)
        
        if not root.left and not root.right:
            result.append(path_list)
posted @ 2018-09-21 14:53  yuyin  阅读(58)  评论(0)    收藏  举报