您的位置:首页 > 其它

[LeetCode] Path Sum 求二叉树中满足要求的路径

2015-04-27 17:24 363 查看
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: