1. 程式人生 > >根據先序和中序遍歷輸出後序遍歷

根據先序和中序遍歷輸出後序遍歷

#include <stdio.h>
#include <stdlib.h>
#define maxn 1000
typedef int ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};
int n,pre[maxn],in[maxn];
BinTree CreatBinTree(int n,int *pre,int *in)
{
    if(n<=0)
        return NULL;
    BinTree temp;
    temp=(TNode*) malloc(sizeof(TNode));
    temp->Data=pre[0];
    temp->Left=NULL;
    temp->Right=NULL;

    int i;
    for(i=0;i<n;i++)
    {
        if(pre[0]==in[i])
            break;
    }
    temp->Left=CreatBinTree(i,pre+1,in);
    temp->Right=CreatBinTree(n-i-1,pre+i+1,in+i+1);
    return temp;

}
void PostorderTraversal(BinTree BT)
{
    if(BT == NULL) return;
    PostorderTraversal(BT->Left);
    PostorderTraversal(BT->Right);
    printf(" %d", BT->Data);
}
int main()
{
    freopen("in.txt","r",stdin);
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",&pre[i]);
    for(int i=0;i<n;i++)
        scanf("%d",&in[i]);
    BinTree BT=CreatBinTree(n,pre,in);
    printf("Postorder:");
    PostorderTraversal(BT);
    printf("\n");
    return 0;
}