zoukankan      html  css  js  c++  java
  • 113. 路径总和 II




    方法一

    class Solution(object):
        def pathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: List[List[int]]
            """
            ans = []
            if not root:
                return ans
            self.dfs(root, sum, ans, [])
            return ans
    
        def dfs(self, root, target, ans, temp):
            if root:
                temp.append(root.val)
                target -= root.val
                left = self.dfs(root.left, target, ans, temp)
                right = self.dfs(root.right, target, ans, temp)
                if not left and not right and target == 0:
                    ans.append(temp + [])
                temp.pop()
                return True
    

    方法二

    class Solution(object):
        def pathSum(self, root, sumt):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: List[List[int]]
            """
            ans = []
            if not root:
                return ans
            stack = [(root, [root.val])]
            while stack:
                node, temp = stack.pop()
                if not node.left and not node.right and sum(temp) == sumt:
                    ans.append(temp)
                if node.left:
                    stack.append((node.left, temp + [node.left.val]))
                if node.right:
                    stack.append((node.right, temp + [node.right.val]))
            return ans[::-1]
    
  • 相关阅读:
    5.Docker服务进程关系
    朴素贝叶斯知识点概括
    k近邻法(KNN)知识点概括
    机器学习的应用实例
    HNU 10111 0-1矩阵
    CSU 1421 Necklace
    Poj 3469 Dual Core CPU
    Poj 2135 Farm Tour
    Poj 3180 The Cow Prom
    HDU 1004 Let the Balloon Rise
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13585704.html
Copyright © 2011-2022 走看看