首页 > 其他 > 详细

113. 路径总和 II

时间:2020-08-30 17:06:06      阅读:77      评论:0      收藏:0      [点我收藏+]

技术分享图片
技术分享图片

方法一

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]

113. 路径总和 II

原文:https://www.cnblogs.com/panweiwei/p/13585704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!