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,最开始想,把所有的路径保存下来,这样肯定是不对的,后来慢慢想到了递归,可以这么想,给定sum,如果root->val != sum, 则继续判断root->left->val,如此类推,这个地方注意,题目要求是“从根到叶子的路径”这个地方错了好几次,最后代码如下
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if None == root:
return False
if root.val == sum and None == root.left and None == root.right:
return True
sum -= root.val
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)