112.路径总和

难度:简单
题目描述:
在这里插入图片描述
思路前瞻:
这题作为简单题,肯定是使用穷举遍历的方法,递归和迭代都可以,类似上一题,257.二叉树的所有路径
题解一:(递归)

# 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: TreeNode, sum: int) -> bool:
        #思路:看这题突然想到了动态规划,不过感觉应该用回溯。
        #这题是简单题,说明可以通过遍历每一条路径来获取答案,搞一波,然后看论文,今天的任务主要看论文,等明天人工智能课再做其他方法吧。
        #递归
        if not root:return False
        res = False
        def helper(node, cur_val):
            cur_val += node.val
            if not node.left and not node.right:
                if cur_val == sum:
                    nonlocal res
                    res = True
            if node.left:
                    helper(node.left, cur_val)
            if node.right:
                    helper(node.right, cur_val)
        helper(root, 0)
        print(res)
        return res

题解一结果:
在这里插入图片描述
题解二:(迭代)
用栈替代递归,每次存当前结点和sum剩余值。

# 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: TreeNode, sum: int) -> bool:
        if not root:return False
        stack = [(root,sum-root.val)]
        while stack:
            cur, last = stack.pop()
            if not cur.left and not cur.right and last == 0:
                return True
            if cur.left:
                stack.append((cur.left, last-cur.left.val))
            if cur.right:
                stack.append((cur.right, last-cur.right.val))
        return False

题解二结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值