写leetcode 112.路径总和的时候对返回值的理解加深了
1. 通过成员变量来传递状态
首先是一个通过成员变量来传递状态的代码,没有用到递归返回值传递:
cpp
class Solution {
public:
int temp = 0;
// 前序遍历
void PathSum(TreeNode* cur, int sum, int targetSum){
sum += cur->val;
if(cur->left == nullptr && cur->right == nullptr){
// 说明是叶子结点,sum 到此为止可以判断了。
if(sum == targetSum){
temp = 1;
return;
}
else
return;
}
if(cur->left != nullptr) PathSum(cur->left, sum, targetSum);
if(cur->right != nullptr) PathSum(cur->right, sum, targetSum);
}
bool hasPathSum(TreeNode* root, int targetSum) {
int sum = 0;
if( root == nullptr)
return 0;
PathSum(root, sum, targetSum);
return (temp == 1);
}
};
2. 误以为"传递"是自动的
然后改成用返回值传递的时候懵了
直接用了PathSum(cur->left, sum, targetSum); 完全没用到它的返回值,以为可以直接return
cpp
class Solution {
public:
// 前序遍历
bool PathSum(TreeNode* cur, int sum, int targetSum){
sum += cur->val;
if(cur->left == nullptr && cur->right == nullptr && sum == targetSum)
return 1;
if(cur->left != nullptr) PathSum(cur->left, sum, targetSum);
if(cur->right != nullptr) PathSum(cur->right, sum, targetSum);
return 0;
}
bool hasPathSum(TreeNode* root, int targetSum) {
int sum = 0;
if( root == nullptr)
return 0;
return PathSum(root, sum, targetSum);
}
};
3.用递归函数返回布尔值进行传递
小修一下,用到返回值
cpp
class Solution {
public:
// 前序遍历
bool PathSum(TreeNode* cur, int sum, int targetSum) {
sum += cur->val;
if (cur->left == nullptr && cur->right == nullptr && sum == targetSum) {
return true;
}
if (cur->left != nullptr && PathSum(cur->left, sum, targetSum)) return true;
if (cur->right != nullptr && PathSum(cur->right, sum, targetSum)) return true;
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) {
return false;
}
return PathSum(root, 0, targetSum);
}
};