python leetcode 112. Path Sum 113. Path Sum II

本文深入探讨了二叉树路径和问题的两种算法实现:PathSum 和 PathSumII。PathSum 检查是否存在从根节点到叶子节点的路径,其节点值之和等于给定的目标和。PathSumII 则返回所有可能的路径,这些路径的节点值之和等于目标和。

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

Path Sum

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        res=[False]
        def dfs(head,mysum,res):
            if res[0]:
                return 
            if not head.left and not head.right:
                if mysum==head.val:
                    res[0]=True 
                return 
            else: 
                if head.left:
                    dfs(head.left,mysum-head.val,res)
                if head.right:
                    dfs(head.right,mysum-head.val,res)
        if not root:
            return False
        dfs(root,sum,res)
        return res[0]

Path Sum II

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        self.res=[]
        def dfs(head,mysum,list1):
            if not head.left and not head.right:
                if mysum==head.val:
                    self.res.append(list1+[mysum])
                return 
            if head.left:
                dfs(head.left,mysum-head.val,list1+[head.val])
            if head.right:
                dfs(head.right,mysum-head.val,list1+[head.val])
                
        if not root:
            return []
        dfs(root,sum,[])
        return self.res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值