如何转换多次调用自己的递归算法?
How do I convert a recursive algorithm that calls itself more than one time?
我有一个函数,它在其主体中调用自己 2 次,我想使用堆栈使其非递归。
我有以下内容来找到二叉树的深度。它可以工作,但我需要将其转换为非递归函数。 我正在考虑使用stack
但这个函数在其代码中调用自己两次,每端一个。如何满足要求?
这是我到目前为止的代码
struct Node{
int value;
Node* left;
Node* right;
};
int depth(const Node* n){
// 0 if null
if(n == nullptr) return 0;
// max(d(left), d(right)) + 1 otherwise
return max(depth(n->left), depth(n->right)) + 1;
}
int depthNoRecursion(const Node* n){
std::stack<Node*> s;
// Do something here...
}
您可以使用一堆保持节点本身和当前级别的对来制作它,类似这样
stack<pair<Node*, int>> stk;
stk.push({root, 1});
int mx_depth = 0;
while(stk.size()){
auto tp = stk.top();
mx_depth = max(mx_depth, tp.second);
stk.pop();
if(tp.first->left != nullptr)
stk.push({tp.first->left, tp.second + 1});
if(tp.first->right != nullptr)
stk.push({tp.first->right, tp.second + 1});
}
相关文章:
- 没有为自己的结构调用列表推回方法
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 在这种情况下,工会成员会调用自己的析构函数吗
- 如何转换多次调用自己的递归算法?
- C :基类调用自己的虚拟函数 - 一个反图案
- 类中的枚举在调用自己的函数时不会改变
- 进行异步调用 - 我必须创建自己的p/s吗?
- C 是否允许函数以不足的参数来调用自己
- 是否可以阻止派生类调用自己的函数?(C++)
- C++抽象基类调用自己的纯虚函数会导致"Undefined reference"
- 在自己的模板类的构造函数中定义并调用模板函数
- 如何创建一个只能由自己的类调用的构造函数
- 为什么派生类调用基类运算符而不是它自己的运算符
- 如何从 dbx 的漂亮打印函数调用 dbx 自己的打印函数
- c++继承.对象调用超类方法而不是自己的方法
- 从其基类捕获的自己的异常类调用方法
- 如何在 C++ 中从类成员函数自己的定义递归调用该函数
- 我不知道如何调用自己的函数!C++
- 如何将对 ole32.dll 的调用重定向到我自己的代理 DLL
- 返回的结构调用它自己的析构函数,用于销毁分配的对象