码迷,mamicode.com
首页 > 其他好文 > 详细

已知一棵树的前序中序,求后序

时间:2015-08-05 16:20:51      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:前中后序

poj 2225

#include<iostream>

#include<fstream>
#include<set>
#include<stack>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<queue>
#include<stdlib.h>
using namespace std;


typedef long long LL;
typedef struct node{
    char data;
    node *left,*right;
}Node,*PNode;
char *p;   //指向pre的指针,一定要设为全局变量,应为即使是回溯过程,也要求Pre的指针不向前移动
void build(char *in,char *pre,PNode *tr)
{
    char *i=in;
    p=pre;
    if(*i==0)
    {
        *tr=NULL;
        return;
    }
    while(1)
    {
        if(*i!=*p)  i++;
        else
        {
            (*tr)=(PNode)malloc(sizeof(Node));
            (*tr)->data=*i;
            //cout<<*i<<endl;
            *i=0;
            break;
        }
    }
    p++;
    build(in,p,&(*tr)->left);
    build(i+1,p,&(*tr)->right);
}
void post(PNode T)
{
    if(T==NULL) return ;
    post(T->left);
    post(T->right);
    printf("%c",T->data);
}
int main( )
{
    //freopen("in.txt","r",stdin);
    char pre[30],in[30];
    while(scanf("%s %s",pre,in)!=EOF)
    {
        PNode T;
        build(in,pre,&T);
        post(T);
        printf("\n");
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

已知一棵树的前序中序,求后序

标签:前中后序

原文地址:http://blog.csdn.net/u014451076/article/details/47298469

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!