剑指OFFER
热身:输入一颗二叉树和一个整数,判断是否存在从根节点到叶节点和为给定整数的路径。
class Solution{
bool ans;
public:
void pathSum(TreeNode* root, int sum, int curSum){
if(!root){
return;
}
curSum += root -> val;
if(!root -> left && !root -> right && curSum == sum){
ans = true;
}
pathSum(root -> left, sum, curSum);
pathSum(root -> right, sum, curSum);
}
bool pathSum(TreeNode* root, int sum){
pathSum(root, sum, 0);
return ans;
}
};
题目描述:输入一颗二叉树和一个整数,输出所有树节点和等于给定整数的路径。
class Solution{
vector<vector<int>> ans;
public:
void pathSum(TreeNode* root, int sum, int curSum, vector<int> temp){
if(!root){
return;
}
curSum += root -> val;
temp.push_back(root -> val);
if(!root -> left && !root -> right && curSum == sum){
ans.push_back(temp);
}
pathSum(root -> left, sum, curSum, temp);
pathSum(root -> right, sum, curSum, temp);
temp.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum){
vector<int> temp;
pathSum(TreeNode* root, sum, 0, temp);
return ans;
}
};
变式:输入一颗二叉树和一个整数,输出树中联系节点和等于给定整数的个数。
class Solution{
public:
int pathSumWithRoot(TreeNode* root, int sum){
if(!root){
return 0;
}
int count = root -> val == sum ? 1 : 0;
count += pathSumWithRoot(root -> left, sum - root -> val);
count += pathSumWithRoot(root -> right, sum - root -> val);
return count;
}
int pathSum(TreeNode* root, int sum){
return root ? pathSumWithRoot(root, sum) + pathSum(root -> left, sum -- root -> val) + pathSum(root -> right, sum - root -> val) : 0;
}
};