空递归函数的更新

What update for a void recursion function

本文关键字:更新 递归函数      更新时间:2023-10-16

嗨,我想使用递归来查找二叉树最后一行中最左边的值。

我尝试以这种方式执行此操作:

class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
int lmValue = root -> val;
int Maxdepth = 0;
Maxdepth = helper(root, 0, Maxdepth, lmValue);
cout << Maxdepth;
return lmValue;
}
private:
int helper(TreeNode* root, int depth, int Maxdepth, int lmValue) {
if (!root) 
return depth;
int leftDepth = helper(root -> left, depth + 1, Maxdepth, lmValue);
int rightDepth = helper(root -> right, depth + 1, Maxdepth, lmValue);
int curDepth = max(leftDepth, rightDepth);
if (curDepth > Maxdepth) {
Maxdepth = curDepth;
lmValue = root -> val;
}
return Maxdepth;
}
};

深度可以更新,因为我返回它。但是,无法更新 lm值。所以答案是错误的。

我找到了一个解决方案,可以这样做:

class Solution {
public:
void findBottomLeftValue(TreeNode* root, int& maxDepth, int& leftVal, int depth) {
if (root == NULL) {
return;
}
//Go to the left and right of each node 
findBottomLeftValue(root->left, maxDepth, leftVal, depth+1);
findBottomLeftValue(root->right, maxDepth, leftVal, depth+1);
//Update leftVal and maxDepth
if (depth > maxDepth) {
maxDepth = depth;
leftVal = root->val;
}
}
//Entry function
int findBottomLeftValue(TreeNode* root) {
int maxDepth = 0;
//Initialize leftVal with root's value to cover the edge case with single node
int leftVal = root->val;
findBottomLeftValue(root, maxDepth, leftVal, 0);
return leftVal;
}
};

我在这里丢失的是解决方案不返回任何内容,但每个变量在每个递归级别都会更新。

这是否意味着如果我什么都不归还,我就归还一切?

作为新手,请给我一些说明。

欣赏!

这是一个非常广泛的问题,但我会尽力给你一个总结。

void findBottomLeftValue(TreeNode* root, int& maxDepth, int& leftVal, int depth) {
// (Recursive calls removed, not relevant to this discussion...)
if (depth > maxDepth) {
maxDepth = depth;
leftVal = root->val;
}
}

类型前面的&表示您正在通过引用传递变量。变量maxDepthleftVal不会复制到函数中,因此对这些变量的赋值将反映在原始值中。这是 C++11 之前的代码中从函数返回多个值的常见习惯用法。下面是一个更简单的示例。

void by_value(int x) {
x++;
}
void by_reference(int& x) {
x++;
}
int main() {
int var = 0;
cout << var << endl; // Prints 0
by_value(var);
cout << var << endl; // Prints 0, since the value was copied to the function
by_reference(var);
cout << var << endl; // Prints 1, since the value was passed by reference
// so the changes in the function are reflected in the
// caller
}