题干:
代码;
class Solution {
public:
bool traversal(TreeNode* node, int count){
if(node == NULL)return false;
if(!node -> left && !node -> right && count == 0)return true;
if(!node -> left && !node -> right && count != 0)return false;
if(node -> left){
count -= node -> left -> val;
if(traversal(node -> left, count))return true;
count += node -> left -> val;
}
if(node -> right){
count -= node -> right -> val;
if(traversal(node -> right, count))return true;
count += node -> right -> val;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == NULL)return false;
return traversal(root, targetSum - root -> val);
}
};
注意count是从父节点开始减的,因为需要不断递归下去所以必须显示出方向,也即node -> left -> val。
另外必须判断root == NULL 情况,不管是在递归函数中还是在主函数中。
类似题:
代码:
class Solution {
private:
void traversal(TreeNode* node, int count, vector<int> tmp, vector<vector<int>> &res){
if(node == NULL)return;
if(!node -> left && !node -> right && count == 0)res.push_back(tmp);
if(!node -> left && !node -> right && count != 0)return;
if(node -> left){
tmp.push_back(node -> left -> val);
count -= node -> left -> val;
traversal(node -> left, count, tmp, res);
count += node -> left -> val;
tmp.pop_back();
}
if(node -> right){
tmp.push_back(node -> right -> val);
count -= node -> right -> val;
traversal(node -> right, count, tmp, res);
count += node -> right -> val;
tmp.pop_back();
}
return;
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int> tmp;
vector<vector<int>> res;
if(root == NULL)return res;
tmp.push_back(root -> val);
traversal(root, targetSum - root -> val, tmp, res);
return res;
}
};
注意,需要在调用前先将根节点值传入tmp内,以及在调用时传入sum - root - > val。