112. 路径总和
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool have = false;
void backtracing(TreeNode* root,int targetSum,int tmp){
if(root == nullptr) return;
tmp += root->val;
if((!root->left) && (!root->right) && (targetSum == tmp)){
have = true;
return;
}
backtracing(root->left,targetSum,tmp);
backtracing(root->right,targetSum,tmp);
}

bool hasPathSum(TreeNode* root, int targetSum) {
backtracing(root,targetSum,0);
return have;
}
};

这道题要注意题意,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum

所以并不只是总和为目标值就可以,即如下:

1
2
3
4
if (targetSum == tmp) {
have = true;
return;
}

你还要保证它是 根节点到叶子节点 的路径,所以应该是如下判断方式:

1
2
3
4
if ((!root - >left) && (!root - >right) && (targetSum == tmp)) {
have = true;
return;
}