lintcode练习 - 246. 二叉树的路径和 II

246. 二叉树的路径和 II

给一棵二叉树和一个目标值,设计一个算法找到二叉树上的和为该目标值的所有路径。路径可以从任何节点出发和结束,但是需要是一条一直往下走的路线。也就是说,路径上的节点的层级是逐个递增的。

样例

对于二叉树:

    1
   / \
  2   3
 /   /
4   2

给定目标值6。那么满足条件的路径有两条:

[
  [2, 4],
  [1, 3, 2]
]

 

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param: root: the root of binary tree
    @param: target: An integer
    @return: all valid paths
    """
    def binaryTreePathSum2(self, root, target):
        # write your code here
        if not root:
            return []
        results = []
        path = []
        self.dfs(root, path, results, target)
        
        return results
    
    def dfs(self, root, path, results, target):
        if root is None:
            return
        path.append(root.val)
        sum = 0
        for i in range(len(path)-1, -1, -1):
            sum += path[i]
            if sum == target:
                results.append(path[i:])
        
        self.dfs(root.left, path, results, target)
        self.dfs(root.right, path, results, target)
        
        path.pop()
        return 
        
        
        

 

点赞