题目链接
1. 判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。
class Solution {
public:
bool travel(TreeNode* root, int count) {
if (!root->right && !root->left && count == 0) {
return true;
}
if (!root->right && !root->left)
return false;
if (root->left) {
if(travel(root->left, count - root->left->val))
return true;
}
if (root->right) {
if (travel(root->right, count - root->right->val))
return true;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
return travel(root, targetSum - root->val);
}
};
2. 找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void travel(TreeNode* root, int count) {
if (!root->right && !root->left && count == 0) {
result.push_back(path);
return ;
}
if (!root->right && !root->left)
return ;
if (root->left) {
path.push_back(root->left->val);
travel(root->left, count - root->left->val);
path.pop_back();
}
if (root->right) {
path.push_back(root->right->val);
travel(root->right, count - root->right->val);
path.pop_back();
}
return ;
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if (!root) return result;
path.push_back(root->val);
travel(root, targetSum - root->val);
return result;
}
};
3. 求该二叉树里节点值之和等于 targetSum 的 路径 的数目。
class Solution {
public:
int res;
void travel(TreeNode* root, int count) {
if (!root->right && !root->left && count == 0) {
res++;
return ;
}
if (!root->right && !root->left)
return ;
if (root->left) {
travel(root->left, count - root->left->val);
}
if (root->right) {
travel(root->right, count - root->right->val);
}
return ;
}
int pathSum(TreeNode* root, int targetSum) {
res = 0;
if (!root) return 0;
travel(root, targetSum - root->val);
return res;
}
};
总结
- 第三题,一直错的原因是没看清题目要求,路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)
- 明天再写吧。