本帖最后由 d173220523 于 2020-8-13 14:13 编辑
[C] 纯文本查看 复制代码 #include <iostream>
#define MaxSize 50 //定义栈中元素的最大个数
typedef struct BiTNode{
char data; //数据域
struct BiTNode *lchild, *rchild; //左、右孩子指针
}BiTNode,*BiTree;
BiTree PrelnCreat(char* in, char* pre, int n){
if(n == 0)
return NULL;
BiTree p = new BiTNode;
p->data = *pre;
for(int i = 0;i < n; i++)
if(in[i] == *pre)
break;
p->lchild = PrelnCreat(in, pre +1, i);
p->rchild = PrelnCreat(in + i + 1, pre + i + 1, n - (i + 1));
return p;
}
BiTree lnPostCreat(char* in, char* post, int n){
if(n == 0)
return NULL;
BiTree p = new BiTNode;
p->data = post[n-1];
for(int i = 0;i < n; i++)
if(in[i] == post[n-1])
break;
p->lchild = PrelnCreat(in, post, i);
p->rchild = PrelnCreat(in + i + 1, post + i, n - (i + 1));
return p;
}
void PostOrder(BiTree T){
if(T){
PostOrder(T->lchild);
PostOrder(T->rchild);
printf("%c",T->data);
}
}
int main(){
char* pre="GDAFEMHZ";
char* in="ADEFGHMZ";
char* post="AEFDHZMG";
BiTree t=lnPostCreat(in,post,8);
PostOrder(t);
//printf("%d",treeDepth(t));
printf("\n");
return 0;
} |