【Leetcode】【python】Path Sum
2017-08-04 06:33
441 查看
题目大意
给定一个数和一棵树,求能否有一条路径上所有叶子结点数值加起来等于给定的数解题思路
递归代码
class 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)
总结
题目要求的和必须是一直贯穿到最下面的叶子结点。不需要考虑中间就到达和的情况这种题目的递归结构都十分相似,通过这种结构来遍历到整个树。
self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
相关文章推荐
- [Leetcode]@python 64. Minimum Path Sum
- [leetcode] @python 112. Path Sum
- LeetCode 64. Minimum Path Sum(Python)
- [LeetCode]题解(python):112-Path Sum
- LeetCode 64. Minimum Path Sum (Python)最优解--Apolo_Shane
- 【leetcode】112. Path Sum(Python & C++)
- 【LeetCode with Python】 Path Sum
- 3.Longest Substring Without Repeating Characters Leetcode Python
- leetcode python 461
- LeetCode-3-Longest-Substring-Without-Repeating-Characters 尺取法+Python数组初始化+ASCLL转换
- [Leetcode,python] Reverse String 反转字符串
- 【LeetCode-Python】292. Nim Game
- [leetcode]Rotate List @ Python
- [leetcode]Copy List with Random Pointer @ Python
- [leetcode: Python]202.Happy Number
- [leetcode] Combinations @ Python [ask for help]
- [LeetCode][JavaScript][Python]Reverse Vowels of a String
- leetcode 【 Subsets II 】python 实现
- LeetCode_Path Sum
- leetcode(12),Ugly Number(python)