已知前序中序求后续

来源:互联网 发布:中国企业寿命统计 知乎 编辑:程序博客网 时间:2024/04/29 09:16

#include<stdio.h>
#include<string.h>
charpre[26];
charin[26];
charpost[26];
        /**三个low和high分别是pre,in和post的起止位置*/
voidPost(intlow1,inthigh1,intlow2,inthigh2,intlow,inthigh)
{
    if(low>high) return;
    charc=pre[low1];
    post[high]=c;   /**把pre[]第一个字符赋给post[]最后一个位置*/
    intk=0;
    while(in[low2+k]!=c)    /**找到pre[]第一个字符在in[]中的位置*/
        k++;
    Post(low1+1,low1+k,low2,low2+k-1,low,low+k-1);
    Post(low1+k+1,high1,low2+k+1,high2,low+k,high-1);
    return;
}
 
intmain()
{
    while(scanf("%s",pre)!=EOF)
    {
        scanf(" %s",in);
        intlen=strlen(pre);
        Post(0,len-1,0,len-1,0,len-1);
        printf("%s",post);
        printf("\n");
    }
    return0;
}





#include <iostream>
#include <cstring>
usingnamespace std;
 
 
 
typedefstruct BinaryTree
    {
    chardata;
    BinaryTree* lchild;
    BinaryTree* rchild;
}BinaryTree;
 
voidRebuildTree(BinaryTree* &Tree,char* pre,char* in,intlen)
    {
    Tree = (BinaryTree*)malloc(sizeof(BinaryTree));
    if(Tree!=NULL)
        {
        if(len<=0)
            {//递归截止条件
            Tree = NULL;
            return;
        }
        intindex = 0;
        while(index<len&&*(pre)!=*(in+index))
            {//寻找当前的root结点(包含子树)
            index++;
        }
        Tree->data = *(pre);
        RebuildTree(Tree->lchild,pre+1,in,index);//去掉root结点
        RebuildTree(Tree->rchild,pre+1+index,in+1+index,len-(index+1));//去掉左边和根节点
    }
    return;
}
 
voidPostOrderTravese(BinaryTree* Tree)
    {//后序遍历输出
    if(Tree==NULL)
        return;
    PostOrderTravese(Tree->lchild);
    PostOrderTravese(Tree->rchild);
    printf("%c",Tree->data);
}
 
 
intmain()
{
    charpre[101];
    charin[101];
    while(scanf("%s %s",pre,in)!=EOF)
        {
        BinaryTree* tree;
        intlength = strlen(pre);
        RebuildTree(tree,pre,in,length);   
        PostOrderTravese(tree);
        cout<<endl;
    }
    return0;
}


阅读全文
0 0