Pretree

来源:互联网 发布:java 动态仪表盘 编辑:程序博客网 时间:2024/05/22 04:47
#include   <iostream> #include <string.h> #include <malloc.h> using namespace std;#define   NULL   0 #define   MaxSize   100 #define   MaxWidth   40 typedef   struct   node { char   data; struct   node   *lchild,*rchild; }BiTree;  //定义二叉树的类型 void PostOrderTraverse(BiTree *root){        if(root!=NULL)    {        PostOrderTraverse(root->lchild);        PostOrderTraverse(root->rchild);        cout<<root->data;    }}void Inorder(BiTree *T){int i;static int N=0;if(T!=NULL)//按右根左遍历二叉树{N++;Inorder(T->rchild);cout<<"\t_________________________\n\t";for(i=1;i<=N;i++)printf("| %c ",(i==N)?T->data:' ');printf("|\n");Inorder(T->lchild);N--;}}BiTree   *restore(char   *ppos,char   *ipos,int   n) { BiTree   *ptr; char   *rpos; int   k; if(n <=0) return   NULL; ptr=(BiTree *)malloc(sizeof(BiTree)); ptr->data=*ppos; ptr->lchild=NULL; ptr->rchild=NULL; for(rpos=ipos;rpos <ipos+n;rpos++) if(*rpos==*ppos) break; k=rpos-ipos; ptr->lchild=restore(ppos+1,ipos,k); ptr->rchild=restore(ppos+1+k,rpos+1,n-1-k); return   ptr; } void   main() {//先序序列:EBADCFHGIKJ  中序序列:ABCDEFGHIJKBiTree   *root; char   *pred=new char[20]; char   *inod=new char[20]; cout << "请输入前序排列: "; cin>> pred; cout <<endl; cout << "请输入中序排列: "; cin>> inod; cout <<endl; root=restore(pred,inod,strlen(pred)); cout <<"后序排列为:";PostOrderTraverse(root);cout <<endl; Inorder(root);}