美文网首页
Leetcode 113 路径总和 II

Leetcode 113 路径总和 II

作者: 钢笔先生 | 来源:发表于2019-08-11 13:39 被阅读0次

Time: 2019-08-11

题目描述

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

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

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


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

返回:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

和前面判断是否存在路径总和的题目类似,也是用DFS的方式来遍历树进行判断。

递归操作有镜像对称的特点,即站在当前层次做了操作,向内一层递归,再退出递归时,状态要是一样的。

代码

# 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, target: int) -> List[List[int]]:
        results = []
        path = []
        curSum = 0
        self.dfs(root, curSum, path, target, results)
        return results
        
    def dfs(self, root, curSum, path, target, results):
        if root == None:
            return 
        
        # 到底递归边界叶子结点
        if root.left == None and root.right == None:
            if curSum + root.val == target:
                results.append(path + [root.val])
                return
        path.append(root.val)
        self.dfs(root.left, curSum + root.val, path, target, results)
        self.dfs(root.right, curSum + root.val, path, target, results)
        path.pop()

这里面的两次self.dfs是同一层次的操作,也可以用下面的形式来写:

# 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, target: int) -> List[List[int]]:
        results = []
        path = []
        curSum = 0
        self.dfs(root, curSum, path, target, results)
        return results
        
    def dfs(self, root, curSum, path, target, results):
        if root == None:
            return 
        
        # 到底递归边界叶子结点
        if root.left == None and root.right == None:
            if curSum + root.val == target:
                results.append(path + [root.val])
                return
        self.dfs(root.left, curSum + root.val, path + [root.val], target, results)
        self.dfs(root.right, curSum + root.val, path + [root.val], target, results)

尤其需要注意的是,在递归到叶子结点时,我们将其作为出口,需要将它本身的值加到path中。

时空复杂度

时间复杂度:O(n)
空间复杂度:O(n)

END.

相关文章

网友评论

      本文标题:Leetcode 113 路径总和 II

      本文链接:https://www.haomeiwen.com/subject/qyzjjctx.html