二叉树遍历

#include <bits/stdc++.h>
using namespace std;

struct Node{
    int m;
    int l;
    int r;
}node[100];

void first(int k){
    cout << node[k].m << " ";
    if(node[k].l != 0)first(node[k].l);
    if(node[k].r != 0)first(node[k].r);
}
void middle(int k){
    if(node[k].l != 0)middle(node[k].l);
    cout << node[k].m << " ";
    if(node[k].r != 0)middle(node[k].r);
}
void last(int k){
    if(node[k].l != 0)last(node[k].l);
    if(node[k].r != 0)last(node[k].r);
    cout << node[k].m << " ";
}

int main(){
    int n;
    cin >> n;
    for(int i = 1;i <= n;i++){
        cin >> node[i].l >> node[i].r;
        node[i].m = i;
    }
    first(1); cout << endl;
    middle(1); cout << endl;
    last(1);

}

前序、中序、后序 遍历 其实蛮简单的注意下位置就行了

原文地址:https://www.cnblogs.com/cunyusup/p/7745741.html