二叉树后序遍历(非递归)

#include<iostream>
#include<stack>

using namespace std;

const int N = 10010;

struct Node{
    int l, r;
}tr[N];

int n, u;
int st[N];

int main(){
    cin >> n >> u; // n个记录,根为u
    
    for(int i = 1; i <= n; i ++){
        int p, l, r; // 结点,左孩子,右孩子
        
        cin >> p >> l >> r;
        tr[p] = {l, r};
    }
    
    stack<int> stk;
    
    stk.push(u);
    
    while(stk.size()){
        int h = stk.top();
        
        if(st[h] == 2){
            cout << h << ' ';
            stk.pop();
        }else if(st[h] == 1){
            st[h] ++;
            if(tr[h].r) stk.push(tr[h].r);
        }else{
            st[h] ++;
            if(tr[h].l) stk.push(tr[h].l);
        }
    }
    
    return 0;
    
}
原文地址:https://www.cnblogs.com/tomori/p/14090393.html