1. 程式人生 > >已知中序和先序|後序,建立二叉樹及三種方式遍歷

已知中序和先序|後序,建立二叉樹及三種方式遍歷

const int maxv= 10000+10;
int n;
int in_order[maxv],post_order[maxv],pre_order[maxv];
int lch[maxv],rch[maxv]; //左右子節點

int build1(int L1,int R1,int L2,int R2)  //通過中序,後序陣列建立二叉樹
{
    if(L1>R1) return 0;
    int root = post_order[R2];
    int p = L1;
    while(in_order[p]!=root) p++;
    int cnt = p-L1;
    lch[root] = build1(L1,p-1,L2,L2+cnt-1);
    rch[root] = build1(p+1,R1,L2+cnt,R2-1);
    return root;
}

int build2(int L1, int R1, int L2, int R2) //通過先序,中序陣列建立二叉樹,返回樹根
{
    if(L1>R1) return 0;
    int root = pre_order[L1];
    int p = L2;
    while(in_order[p]!=root) p++;
    int cnt = p-L2;
    lch[root] = build2(L1+1,L1+cnt,L2,p-1);
    rch[root] = build2(L1+cnt+1,R1,p+1,R2);
    return root;
}



void post_reverse(int root)  //後序遍歷
{
    if(root)
    {
        post_reverse(lch[root]);
        post_reverse(rch[root]);
        printf("%d ",root);
    }
}

void in_reverse(int root)  //中序遍歷
{
    if(root)
    {
        post_reverse(lch[root]);
        printf("%d ",root);
        post_reverse(rch[root]);
    }
}

void pre_reverse(int root)  //先序遍歷
{
    if(root)
    {
        printf("%d ",root);
        post_reverse(lch[root]);
        post_reverse(rch[root]);
    }
}