题目:
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.
Note: A leaf is a node with no children.
思路:
对于每个node的判断,总共分三种情况:
- 无左子树,无右子树。此节点为叶子节点,如果sum==叶子节点值,返回true;否则返回false。
- 有左子树,无右子树。递归判断左子树。
- 无左子树,有右子树。递归判断右子树。
- 有左子树,有右子树。递归判断左、右子树,有任意一个符合条件,则返回true;否则返回false。
代码实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool f(TreeNode* root, int sum){
bool left_ret = false, right_ret = false;
if (root->left == nullptr && root->right == nullptr){
if (root->val == sum){
return true;
}
return false;
}else if(root->left == nullptr){
left_ret = f(root->right, sum-root->val);
}else if(root->right == nullptr){
right_ret = f(root->left, sum-root->val);
}else{
left_ret = f(root->right, sum-root->val);
if (left_ret == true){
return true;
}
right_ret = f(root->left, sum-root->val);
}
return left_ret || right_ret;
}
bool hasPathSum(TreeNode* root, int sum) {
if (root == nullptr){
return false;
}
return f(root, sum);
}
};
discuss:
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
if (!root->left && !root->right && root->val == sum)
return true;
else
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); // 凡是涉及到递归求和,多数算法都用减的形式。
}
};
二叉树路径和判断
本文探讨了在给定的二叉树中寻找一条从根节点到叶子节点的路径,使得路径上所有节点的值之和等于给定的数值。通过递归算法,我们检查每个节点,如果达到叶子节点且剩余的和等于该节点值,则返回真;否则继续在左子树和右子树中递归查找。
551

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



