1、递归版
template <typename T, typename VST>
void travPre_R(BinNode<T>* x, VST& visit){
if(!x) return;
visit(x->data);
travPre_R(x->lc, visit);
travPre_R(x->rc, visit);
}
2、迭代版
template <typename T, typename VST>
static void visitAlongLeftBranch(BinNode<T>* x, VST& visit, Stack<BinNode<T>*>& S){
while(x){
visit(x->data);
S.push(x->rc);
x = x->lc;
}
}
//先序遍历迭代版版本2代码
template <typename T, typename VST>
void travPre_I2(BinNode<T>* x, VST& visit){
Stack<BinNode<T>*> S;
while(true){
visitAlongLeftBranch(x, visit, S);
if(S.empty()) break;
x = S.pop();
}
}
来源:CSDN
作者:Xiaaaaaacy
链接:https://blog.csdn.net/Nemoosi/article/details/104538646