首页 > 其他 > 详细

leetcood学习笔记-437-路径总和③**

时间:2019-03-29 21:20:32      阅读:131      评论:0      收藏:0      [点我收藏+]

题目描述:

 

方法一:栈

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        count = 0
        if root == None:
            return count
        stack = [(root,[root.val])]
        while stack != []:
            tree,number = stack.pop()
            for i in number:
                if i == sum:
                    count += 1
            if tree.left:
                stack.append((tree.left,[tree.left.val]+[_+tree.left.val for _ in number]))
            if tree.right:
                stack.append((tree.right,[tree.right.val]+[_+tree.right.val for _ in number]))
        return count

方法二:

class Solution:
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        self.result = 0
        self.sum = sum
        current_sum_list = []

        def current_sum(root, current_sum_list):
            if root is not None:
                for i in range(len(current_sum_list)):
                    current_sum_list[i] += root.val
                    if current_sum_list[i] == self.sum:
                        self.result += 1
                current_sum_list.append(root.val)
                if root.val == self.sum:
                    self.result += 1
                # print(current_sum_list)

                current_sum(root.left, current_sum_list[:])
                current_sum(root.right, current_sum_list[:])

        current_sum(root, current_sum_list)

        return self.result

方法三:最快

class Solution(object):
    def pathSum(self, root, sum):
        from collections import defaultdict
        lookup = defaultdict(int)
        lookup[0] = 1
        self.res = 0
        
        def helper(root,curSum):
            if not root:
                return 
            curSum += root.val
            self.res += lookup[curSum - sum]
            lookup[curSum] += 1
            helper(root.left,curSum)
            helper(root.right,curSum)
            lookup[curSum] -= 1
        helper(root,0)
        return self.res

 

leetcood学习笔记-437-路径总和③**

原文:https://www.cnblogs.com/oldby/p/10623667.html

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