LeetCode Path Sum II

LeetCode解题之Path Sum II


原题

找出一棵二叉树全部的从根节点到某一叶子节点的路径,该路径上全部节点的和为一个特定值。

注意点:

样例:

输入:

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

输出:

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

解题思路

Path Sum 是推断是否有这样一条路径,如今要把全部的路径都求出来。那仅仅要在dfs时将符合要求的路径增加到结果集。

注意增加结果集的数据不要是引用。否则可能之后会再次被改动。

AC源代码

# 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]]
        """
        result = []
        self._pathSum(root, sum, [], result)
        return result

    def _pathSum(self, root, sum, curr, result):
        if not root:
            return
        sum -= root.val
        if sum == 0 and root.left is None and root.right is None:
            result.append(curr + [root.val])
        if root.left:
            self._pathSum(root.left, sum, curr + [root.val], result)
        if root.right:
            self._pathSum(root.right, sum, curr + [root.val], result)


if __name__ == "__main__":
    None

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

posted @ 2017-07-27 20:48  yjbjingcha  阅读(361)  评论(0)    收藏  举报