• LeetCode 113. 路径总和 II


    113. 路径总和 II

    Difficulty: 中等

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

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

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

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

    返回:

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

    Solution

    Language: 全部题目

    解决的思路依旧是递归,跟路径总和的第一道题不同,这道题需要把所有路径的可能性都找出来。递归终止的条件是sum==root.val,最终我们需要的是满足此条件的那一条“路径”。如果不太好理解这个递归,不妨把问题缩小成一颗只有根节点为7和左右节点分别为7和2的二叉树,此时sum等于13,左子树pathSum(7, 2),那么tmp为[],最终pathSum(7, 2)的结果也为[](因为tmp为[],所以列表表达式[[root.val] + i for i in tmp]的返回是[])。右子树pathSum(2,2)返回的结果为[[2]],所以最终的结果为tmp=[[2]],返回[[11] for i in [[2]]]。递归不太好理解的话,动手画画。

    参考:Python solutions (Recursively, BFS+queue, DFS+stack) - LeetCode Discuss

    # 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, sum: int) -> List[List[int]]:
            if not root: 
                return []
            if not root.left and not root.right and sum == root.val:
                return [[root.val]]
            tmp = self.pathSum(root.left, sum-root.val) + self.pathSum(root.right, sum-root.val)
            return [[root.val] + i for i in tmp]
    

    迭代法:

    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
            if not root:
                return []
            res = []
            self.dfs(root, targetSum, res, [])
            return res
    
        def dfs(self, root, target, res, path):
                path.append(root.val)
                if not root.left and not root.right and sum(path) == target:
                    res.append(path[:])
    
                if root.left:
                    self.dfs(root.left, target, res, path)
                if root.right:
                    self.dfs(root.right, target, res, path)
                path.pop()
    
  • 相关阅读:
    8VC Venture Cup 2016
    8VC Venture Cup 2016
    8VC Venture Cup 2016
    HDU 5627 Clarke and MST &意义下最大生成树 贪心
    HDU 5626 Clarke and points 平面两点曼哈顿最远距离
    《花开物语》观后感
    Codeforces Round #146 (Div. 1) B. Let's Play Osu! dp
    Codeforces Round #146 (Div. 1) A. LCM Challenge 水题
    Educational Codeforces Round 7 E. Ants in Leaves 贪心
    Educational Codeforces Round 7 D. Optimal Number Permutation 构造题
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14056345.html
Copyright © 2020-2023  润新知