3-30树的练习

#include<stdio.h>
#include<cstring>
struct node{
    node *lchild;
    node *rchild;
    char x;
}tree[50];
int loc;
char str1[30],str2[30];
node *create()
{
    tree[loc].lchild = tree[loc].rchild = NULL;
    return &tree[loc ++];
}
node *build(int s1,int e1,int s2,int e2)
{
    node *ret = create();
    ret -> x = str1[s1];
    int rootidx;
    for(int i = s2; i <= e2; i++)
    {
        if(str2[i] == str1[s1])
        {
            rootidx = i;
            break;
        }
    }
    if(rootidx != s2)
        ret -> lchild = build(s1 + 1,s1 + rootidx - s2, s2,rootidx - 1);
    if(rootidx != e2)
        ret -> rchild = build(s1 + rootidx - s2 + 1,e1,rootidx + 1,e2);
    return ret;
}
void preorder(node *p)
{
    if(p -> lchild != NULL)
        preorder(p->lchild);
    if(p -> rchild != NULL)
        preorder(p->rchild);
    printf("%c",p->x);
}
int main()
{
    while(scanf("%s",str1) != EOF)
    {
        scanf("%s",str2);
        node *p = build(0,strlen(str1) - 1,0,strlen(str2) - 1);
        preorder(p);
        printf("\n");
    } 
    return 0;
}

 

posted on 2013-03-31 18:38  lgy111  阅读(122)  评论(0)    收藏  举报

导航