二叉樹:根據二叉樹的先序遍歷序列和中序遍歷序列,輸出該二叉樹的後序遍歷序列

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
    int data;
    struct node *lchild,*rchild;
};
struct node *creat(int n,char *a,char *b)
{
    struct node *root;
    char *p;
    if(n==0)
        return NULL;
    root=(struct node *)malloc(sizeof(struct node));
    root->data=a[0];
    for(p=b; p!='\0'; p++)
        if(*p==a[0])
            break;                           //尋找中序遍歷中的相同結點,將數分成左子樹和右子數
    int t;
    t=p-b;
    root->lchild=creat(t,a+1,b);             //左子樹
    root->rchild=creat(n-t-1,a+t+1,p+1);     //右子樹
    return root;
}
void houxu(struct node *root)
{
    if(root)
    {
        houxu(root->lchild);
        houxu(root->rchild);
        printf("%c",root->data);
    }
}
int main()
{
    int m;
    struct node *root;
    root=(struct node *)malloc(sizeof(struct node));
    char a[100],b[100];
    scanf("%s %s",a,b);
    m=strlen(a);
    root=creat(m,a,b);
    houxu(root);
    printf("\n");
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章