如何转换多次调用自己的递归算法?

How do I convert a recursive algorithm that calls itself more than one time?

本文关键字:调用 自己的 递归算法 何转换 转换      更新时间:2023-10-16

我有一个函数,它在其主体中调用自己 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});
}