1、while(ino!=ch&ino) i+;if(ino=ch) return i;else return -1; void CrtBT(BiTree *T, char pre, char ino, int ps, int is, int n ) /*已知preps.ps+n-1为二叉树的先序序列,inois.is+n-1为二叉树的中序序列,本算法由此两个序列构造二叉链表*/ int k;if (n=0) T=NULL;k=Search(ino, preps);/*在中序序列中查询*/ if (k= -1) T=NULL;puts(错误!n);T= (BiTree*)malloc(sizeof
2、(BiTree);if (T=NULL) exit(1);T-data = preps;if (k=is) T-lchild = NULL;CrtBT(T-lchild ,pre ,ino ,ps+1 ,is ,k-is );if (k=is+n-1) T-rchild = NULL;rchild, pre, ino, ps+1+(k-is), k+1, n-(k-is)-1 ); /* end CrtBT */ void postorder(BiTree *t)/递归先序遍历 if(t!=NULL) printf(%ct,t-data);postorder(t-lchild);rchild)
3、;void main() char presize,inosize;int ps,is,n;BiTree *T=NULL;enter:scanf(%s,pre);,ino);CrtBT(T,pre,ino,0,0,strlen(pre);postorder(T);getchar();本贴来自ZDNetChina中文社区 ,本贴地址:/ Rebuild a binary tree / vlr: preorder sequence / lvr: inorder sequence / number of node BinTreeNode *Rebuild(char *vlr, char *lvr,
4、int n) if(n = 0) return NULL ; / Find root in inorder sequence int k = 0; while(lvrk != vlr0) k+ ; BinTreeNode * temp = new BinTreeNode(); if(lvrk = #) / leaf node temp = NULL ; else temp-data = lvrk; / Build rootleft = Rebuild(vlr + 1, lvr, k) ; / Build left treeright = Rebuild(vlr + 1 + k, lvr + k
5、 + 1, n - k - 1) ; / Build right tree return temp ;malloc.h#define MaxSize 100typedef char ElemType;typedef struct BiTNode/*二叉链表数据结构定义*/ DataType data; struct BiTNode *lchild,*rchild;typedef struct node ElemType data; struct node*lchild; struct node*rchild;BTree;BTree node(char *pre,char *inorder,in
6、t len) char *p,*q; BTree root; int i; if(lendata = pre0; /根节点lch = NULL;rch = NULL; i = 0; /i表示根节点在中序中的位置 while(i if (k=is) T- else CrtBT(T- if (k=is+n-1) T- void postorder(BiTree *t)/puts(typedef struct BTNode struct BTNode *lchild,*rchild;BiTree *CreateBT1(char *pre, char*in,int n) BiTree *s; char *p; int k; if(ndata=*pre; for(p=in;plchind=CreateBT1(pre+1,in,k)rchild=CreateBT1(pre+k+1,p+1,n-k-1); return s;
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1