博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】Path Sum
阅读量:4596 次
发布时间:2019-06-09

本文共 1048 字,大约阅读时间需要 3 分钟。

题目简述:

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:

Given the below binary tree and sum = 22,
5
/ 4 8
/ / 11 13 4
/   7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

解题思路:

注意这里的路径必须是从根到叶子(必须到叶子!)。这里有个神奇的现象sum -= root.val这句不谢的话,下面改成if sum == root.val and root.left == None and root.right == None:就过不了

# Definition for a  binary tree node# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    # @param root, a tree node    # @param sum, an integer    # @return a boolean    def hasPathSum(self, root, sum):        ret = False        if root == None:            return ret        sum -= root.val        if sum == 0 and root.left == None and root.right == None:            ret = True        return ret or self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum)

转载于:https://www.cnblogs.com/MrLJC/p/4376282.html

你可能感兴趣的文章
(转载)rabbitmq与springboot的安装与集成
查看>>
C2. Power Transmission (Hard Edition)(线段相交)
查看>>
STM32F0使用LL库实现SHT70通讯
查看>>
Atitit. Xss 漏洞的原理and应用xss木马
查看>>
MySQL源码 数据结构array
查看>>
(文件过多时)删除目录下全部文件
查看>>
T-SQL函数总结
查看>>
python 序列:列表
查看>>
web移动端
查看>>
pythonchallenge闯关 第13题
查看>>
linux上很方便的上传下载文件工具rz和sz使用介绍
查看>>
React之特点及常见用法
查看>>
【WEB前端经验之谈】时间一年半,或沉淀、或从零开始。
查看>>
优云软件助阵GOPS·2017全球运维大会北京站
查看>>
linux 装mysql的方法和步骤
查看>>
poj3667(线段树区间合并&区间查询)
查看>>
51nod1241(连续上升子序列)
查看>>
SqlSerch 查找不到数据
查看>>
集合相关概念
查看>>
Memcache 统计分析!
查看>>