[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
return true, as there exist a root-to-leaf path
题目意思是说给定一个二叉树后判断是否存在从根到叶的一条路径,让该路径上的接点之和为sum,最开始想,把所有的路径保存下来,这样肯定是不对的,后来慢慢想到了递归,可以这么想,给定sum,如果root->val != sum, 则继续判断root->left->val,如此类推,这个地方注意,题目要求是“从根到叶子的路径”这个地方错了好几次,最后代码如下
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.
题目意思是说给定一个二叉树后判断是否存在从根到叶的一条路径,让该路径上的接点之和为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)
相关文章推荐
- [LeetCode] Path Sum 求二叉树中满足要求的路径
- [LeetCode] Path Sum 二叉树的路径和
- 每天一道LeetCode-----计算二叉树的最大路径和,路径只需要从一个节点到达另一个节点,无其他要求
- 【leetcode 二叉树路径和】Path Sum 和 Path Sum II
- leetcode 64. Minimum Path Sum-最小路径和|动态规划
- Leetcode 64. Minimum Path Sum 最小路径和 解题报告
- 【Leetcode】257 Binary Tree Paths 二叉树的路径
- 子集系列(二) 满足特定要求的子集,例 [LeetCode] Combination, Combination Sum I, II
- LeetCode 437. Path Sum III 题解 和固定的二叉树路径数目
- [LeetCode] 递归求解二叉树路径之和是否等于给定值(2)
- 【LeetCode】二叉树的所有路径 - Easy(FB,Google)
- LeetCode 112. Path Sum(路径和)
- [LeetCode] Binary Tree Paths 二叉树路径
- 找出二叉树中满足某种条件的所有路径
- LeetCode---- 二叉树中,找出和为某值的所有路径
- leetCode 112 二叉树路径求和问题
- [LeetCode] 124. Binary Tree Maximum Path Sum 求二叉树的最大路径和
- 找出二叉树中满足某种条件的所有路径
- [Leetcode] Path Sum路径和
- <LeetCode><Easy> 112 Path Sum --二叉树深度优先遍历