已知一棵二叉樹的中序遍歷和後序遍歷,求二叉樹的先序遍歷

#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[n - 1];
    for(p = b; p != '\0'; p++)
        if(*p == a[n - 1])
            break;
    int t = p - b;
    root -> lchild = creat(t, a, b);
    root -> rchild = creat(n - t - 1, a + t, p + 1);
    return root;
}
void xianxu(struct node *root)
{
    if(root)
    {
        printf("%c",root->data);
        xianxu(root->lchild);
        xianxu(root->rchild);
    }
}
int main()
{
    int m, t;
    scanf("%d", &t);
    getchar();
    while(t--)
    {
        struct node *root;
        root=(struct node *)malloc(sizeof(struct node));
        char a[100],b[100];
        scanf("%s %s",b,a);
        m=strlen(a);
        root=creat(m,a,b);
        xianxu(root);
        printf("\n");
    }
}

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