Path Sum - LeetCode
2015-02-09 16:50
169 查看
Path Sum - LeetCode
题目:
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->2which sum is 22.
分析:
就是一个简单的递归计算来判断。代码:
class Solution: # @param root, a tree node # @param sum, an integer # @return a boolean def hasPathSum(self, root, sum): return self.bfs(root,0,sum) def bfs(self,root,v,sum): if not root: return False if root.left == None and root.right == None: return v+root.val == sum return self.bfs(root.left,v+root.val,sum) or self.bfs(root.right,v+root.val,sum)
相关文章推荐
- [LeetCode] Path Sum
- leetcode112 Path Sum
- LeetCode112——Path Sum
- LeetCode--Path Sum
- [Leetcode] 64. Minimum Path Sum
- 【LeetCode】 112. Path Sum
- 【leetcode】Path Sum
- LeetCode_Path Sum
- Leetcode: mimimum depth of tree, path sum, path sum II
- LeetCode *** 112. Path Sum
- [LeetCode][Java] Path Sum
- [LeetCode] Path Sum 求二叉树中满足要求的路径
- leetcode: Path Sum
- [LeetCode]64.Minimum Path Sum
- [leetcode]112. Path Sum
- [LeetCode116]Path Sum
- 和大神们学习每天一题(leetcode)-Path Sum
- [LeetCode] Path Sum
- [leetcode] Path Sum
- Leetcode 64. Minimum Path Sum (Medium) (cpp)