博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode By Python]112. Path Sum
阅读量:4055 次
发布时间:2019-05-25

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

题目:

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.

代码+调试:

class TreeNode:    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution(object):    def hasPathSum(self, root, sum):        """        :type root: TreeNode        :type sum: int        :rtype: bool        """        if root == None:            return False        if root.left == None and root.right==None:            return sum==root.val        return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)if __name__ == '__main__':      l1_1 = TreeNode(1)      l1_2 = TreeNode(2)      l1_3 = TreeNode(3)      l1_4 = TreeNode(4)     l1_5 = TreeNode(5)     l1_6 = TreeNode(6)         l1_1.left = l1_2      l1_1.right = l1_3     l1_2.left = l1_4    l1_2.right = l1_5    l1_4.left = l1_6       l3 = Solution().hasPathSum(l1_1,34)      print l3

转载地址:http://azhci.baihongyu.com/

你可能感兴趣的文章
IntelliJ IDEA 下的svn配置及使用的非常详细的图文总结
查看>>
【IntelliJ IDEA】idea导入项目只显示项目中的文件,不显示项目结构
查看>>
ssh 如何方便的切换到其他节点??
查看>>
JSP中文乱码总结
查看>>
Java-IO-File类
查看>>
Java-IO-java的IO流
查看>>
Java-IO-输入/输出流体系
查看>>
Java实现DES加密解密
查看>>
HTML基础
查看>>
Java IO
查看>>
Java NIO
查看>>
Java大数据:Hbase分布式存储入门
查看>>
Java大数据:全文搜索引擎Elasticsearch入门
查看>>
大数据学习:Hadoop入门学习书单
查看>>
大数据学习:Spark SQL入门简介
查看>>
大数据学习:Spark RDD操作入门
查看>>
大数据框架:Spark 生态实时流计算
查看>>
大数据入门:Hive和Hbase区别对比
查看>>
大数据入门:ZooKeeper工作原理
查看>>
大数据入门:Zookeeper结构体系
查看>>