lc113.路径总和II

 

题目链接

此题与jz034.二叉树中和为某一值的路径相同,这个算法的时间复杂度是O(N),空间复杂度是O(N)。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:

    def pathSum(self, root: TreeNode, tar: int) -> List[List[int]]:
        stack, res = [], []
        def dfs(node):
            if not node:
                return 
            stack.append(node.val)
            if not node.left and not node.right and sum(stack) == tar:
                res.append(list(stack))
            dfs(node.left)
            dfs(node.right)
            stack.pop()

        dfs(root)
        return res