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) 来获得相关源码。

你可能感兴趣的:(LeetCode,算法,python,二叉树,DFS)