poj2255

来源:互联网 发布:淘宝假货 猪哼少 编辑:程序博客网 时间:2024/05/16 03:45

本题为给出前序遍历与中序遍历要求给出后序遍历

前序遍历的结构为 根 左子树 右子树 

中序遍历的结构为 左子树 根 右子树

故可以从前序遍历中获取根节点的值在中序遍历中获取左右子树的长度 从而进行递归

写此题时刚学树 代码很丑

#include<iostream>#include<stdio.h>using namespace std;template <class Type>struct node{    Type data;    struct node *lchild;    struct node *rchild;};typedef node<char> Tree;void TR(char *a,char *b,Tree **t){    if(*t==NULL)return;    char *pr,*ir,*nr;    pr=a;    ir=b;    nr=b;    while(*pr!=*ir)ir++;//    *t=new Tree;    (*t)->data=*ir;    (*t)->lchild=*t;//为了不让指针为NULL    (*t)->rchild=*t;//为了不让指针为NULL    *ir='0';//遍历过的置'0'    //判断左右子树是否存在    if(*(ir-1)=='\0'||*(ir-1)=='0')(*t)->lchild=NULL;    if(*(ir+1)=='\0'||*(ir+1)=='0')(*t)->rchild=NULL;    TR(pr+1,nr,&((*t)->lchild)); //左支树递归    TR(pr+(ir-nr)/sizeof(char)+1,ir+1,&((*t)->rchild));//右支树递归}void Pcout(Tree *t){    if(t==NULL)return;    Pcout(t->lchild);    Pcout(t->rchild);    cout<<t->data;}int main(){    //freopen("test","r",stdin);    char a[28],b[28];    Tree *t;    a[0]='0';    b[0]='0';    while (scanf("%s%s",a+1,b+1) != EOF)    {        TR(a+1,b+1,&t);        Pcout(t);        cout<<endl;    }    return 0;}


0 0
原创粉丝点击