112.113. 路径总和 I,II(简单,中等)

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

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

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

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root:
            return False
        sum-=root.val
        if sum==0:
            if root.left is None and root.right is None:
                return True
        return self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum)

执行用时: 68 ms, 在Path Sum的Python3提交中击败了81.30% 的用户

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

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

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

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]
# 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, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        def dummy(root,summ,l):
            if not root:
                return l
            if not root.left and not root.right:
                if summ+root.val==sum:
                    result.append(l+[root.val])
            if root.left:
                dummy(root.left,summ+root.val,l+[root.val])
            if root.right:
                dummy(root.right,summ+root.val,l+[root.val])
        result=[]
        dummy(root,0,[])
        return result
        

执行用时: 72 ms, 在Path Sum II的Python3提交中击败了92.86% 的用户

猜你喜欢

转载自blog.csdn.net/weixin_42234472/article/details/84899462
今日推荐