Input:
number of the first line of the input node. Continued input information in the n-th row of each node according to the following format, one row for each node.
left right ID
ID of node numbers, left child node numbers to the left, right for the right child node numbers. When the left child node does not exist (right) -1
Outputs:
a first output line of a preorder traversal of the node numbers
of the second line of output nodes preorder number
after the output node number of the third order traversal row
Code
#include<stdio.h>
#define MAX 10000
#define NIL -1
struct Node{
int p, l, r;
};
struct Node T[MAX];
int n;
void preParse(int u){
if(u == NIL) return;
printf(" %d", u);
preParse(T[u].l);
preParse(T[u].r);
}
void inParse(int u){
if(u == NIL) return;
inParse(T[u].l);
printf(" %d", u);
inParse(T[u].r);
}
void postParse(int u){
if(u == NIL) return;
postParse(T[u].l);
postParse(T[u].r);
printf(" %d", u);
}
int main(){
int i, v, l, r, root;
scanf("%d", &n);
for(i = 0; i < n; i++){
T[i].p = NIL;
}
for(i = 0; i < n; i++){
scanf("%d %d %d", &v, &l, &r);
T[v].l = l;
T[v].r = r;
if(l != NIL) T[l].p = v;
if(r != NIL) T[r].p = v;
}
for(i = 0; i < n; i++) if(T[i].p == NIL) root = i;
printf("Preorder\n");
preParse(root);
printf("\n");
printf("Inorder\n");
inParse(root);
printf("\n");
printf("Postorder\n");
postParse(root);
printf("\n");
return 0;
}