本题想到的解法是对二叉树进行深度搜索,并记录路径和,当节点为叶子节点时,将路径和与目标值进行判断,如果相等则返回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 dfs(TreeNode* root, int sum, int targetSum){
if(root->left == nullptr && root->right == nullptr){
sum += root->val;
if(sum == targetSum){
return true;
}
else{
return false;
}
}
sum += root->val;
bool l_val = 0;
bool r_val = 0;
if(root->left){
l_val = dfs(root->left, sum, targetSum);
}
if(root->right){
r_val = dfs(root->right, sum, targetSum);
}
return l_val || r_val;
}
bool hasPathSum(TreeNode* root, int targetSum) {
int sum = 0;
if(root == nullptr){
return false;
}
return dfs(root, sum, targetSum);
}
};
力扣官方的递归更为精妙,顺便记录一下:将问题转化为是否存在从当前节点的子节点到叶子的路径,满足其路径和为 sum - val。
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (root == nullptr) {
return false;
}
if (root->left == nullptr && root->right == nullptr) {
return sum == root->val;
}
return hasPathSum(root->left, sum - root->val) ||
hasPathSum(root->right, sum - root->val);
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/path-sum/solutions/318487/lu-jing-zong-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
标签:right,TreeNode,val,sum,路径,力扣,left,root,总和
From: https://blog.csdn.net/why_12134/article/details/139604110