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.
【问题分析】
这是一个比较简单的问题,有多种解决方法,首先把问题分析清楚,就比较简单了
题目的意思是查找是否存在一条从根节点都页节点的路径,它们的和为给定的数字。
方法:递归
递归方法很容易想到,对根节点,如果满足条件可以直接返回true,否则递归处理根节点的左孩子和右孩子,并且将sum减去根节点val
【AC代码】
贴出代码,应该没什么问题
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (root == NULL) { //不存在满足条件的情况
return false;
}
if (root->left == NULL && root->right == NULL) { //<span style="font-family: Arial;">结束条件,根节点满足条件</span>
return (root->val == sum);
}
bool isLeft = false;
bool isRight = false;
if (root->left) {
isLeft = hasPathSum(root->left, sum - root->val); //递归左子树
}
if (root->right) {
isRight = hasPathSum(root->right, sum - root->val); //递归右子树
}
return isLeft || isRight;
}
};
本文介绍了一种简单的方法来判断二叉树中是否存在从根节点到叶子节点的路径,使得这条路径上所有节点值之和等于给定的数值。通过递归方式实现,提供了完整的C++代码示例。
440

被折叠的 条评论
为什么被折叠?



