空递归函数的更新
What update for a void recursion function
嗨,我想使用递归来查找二叉树最后一行中最左边的值。
我尝试以这种方式执行此操作:
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;
}
}
类型前面的&
表示您正在通过引用传递变量。变量maxDepth
和leftVal
不会复制到函数中,因此对这些变量的赋值将反映在原始值中。这是 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
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 递归函数有效,但无法记忆
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么递归函数的最终输出是 5?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 如何将记忆应用于此递归函数?
- 如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
- 无穷大而循环时具有递归函数
- 即使没有调用这个递归函数,它是如何工作的?
- 如何使此递归函数从给定的起始位置返回最小的整数?
- 此递归函数的每次迭代的值存储在哪里?
- 可以清除递归函数中的变量吗?
- 如何在递归函数调用中返回当前函数值
- 递归函数 c++ 的复杂性
- 这个递归函数有什么作用?运行时的复杂性是多少?
- 任何人都可以查明我的递归函数中的错误吗?
- 递归函数的返回类型推导
- 空递归函数的更新
- 连续文件更新,递归函数