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

本文深入探讨了二叉树路径和问题的两种解决方法:判断二叉树中是否存在一条从根节点到叶子节点的路径,其节点值之和等于给定的目标和;以及寻找所有这样的路径并返回。通过具体示例,详细解释了算法的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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

示例: 
给定如下二叉树,以及目标和 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% 的用户

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值