Leetcode算法刷题:第112题 Path Sum

Path Sum

题目

给予一个二叉树,和一个值su,寻找是否有一个从根节点到叶节点的和为su,有则返回True,没有为False。比如:

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

hasPathSum(self, root, 22) 将返回True
节点为:

class TreeNode:
   def __init__(self, x):
      self.val = x
      self.left = None
      self.right = None

解题思路

class Solution:
    # @param {TreeNode} root
    # @param {integer} sum
    # @return {boolean}
    def hasPathSum(self, root, su):
        flag = False
        if not root:
            return flag
        su -= root.val
        if su == 0 and (not root.left) and (not root.right):
            flag = True
        return flag or self.hasPathSum(root.left, su) or self.hasPathSum(root.right, su)
posted @   Eric_Nirvana  阅读(162)  评论(0编辑  收藏  举报
编辑推荐:
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
点击右上角即可分享
微信分享提示