1086. Tree Traversals Again

这个题让我想起“递归改写成循环”这个问题,所有递归都可以用步骤标记的方式改写成循环,尤其是树的非递归式遍历挺有意思

#include<stack>
#include<iostream>
using namespace std;
struct node{int lch,rch;};
node v[60];
int pop[60],id[60];
void post(int k){
  if(!k)return ;
  static int first=0;
  post(v[k].lch);
    post(v[k].rch);
    cout<<(first++?" ":"")<<k;
}
int main(){
  int n,root,flag=0;cin>>n;
  stack<int>st;
  for(int i=0;i<2*n;++i){
    string s;cin>>s;
    if(s[1]=='u') {
      cin>>id[i];
      if(flag==0) root=id[i],++flag;}
    else pop[i]=true;
  }
  for(int i=0;i<2*n-1;++i){
    if(!pop[i])st.push(id[i]);
    if(!pop[i]&&!pop[i]) v[st.top()].lch=id[i+1];
    if(pop[i]&&!pop[i+1]) v[st.top()].rch=id[i+1];
    if(pop[i]) st.pop();
  }
  post(root);
}


你可能感兴趣的:(1086. Tree Traversals Again)