思路:
先序 | 根——左——右 |
---|---|
中序 | 左——根——右 |
后序 | 左——右——根 |
1.在先序中找到根节点
2.在中序中找到根节点
3.求左子树的长度
4.求右子树的长度
5.建立左子树
6.建立右子树
7.输出后序
AC代码:
#include <iostream>
#include<cstring>
using namespace std;
//建立二叉树
struct btnode
{
char data;
struct btnode *lchild,*rchild;
};
//s[]先序,r[]中序
char s[201],r[201];
int length;
struct btnode *createbitree(int str1,int str2,int length)
{
int root;
int i;
int llen,rlen;
struct btnode *p;
if(length==0) return NULL;
//1.在先序中找到根节点
root=s[str1];
//2.在中序中找到根节点
i=str2;
while(r[i]!=root) i++;
//3.左子树的长度
llen=i-str2;
//4.右子树的长度
rlen=length-llen-1;
//5.建立左子树
p=new struct btnode;
p->data=root;
p->lchild=createbitree(str1+1,str2,llen);
//6.建立右子树
p->rchild=createbitree(str1+1+llen,str2+1+llen,rlen);
return (p);
}
//输出后序
void postorder(struct btnode *t)
{
if(t)
{
postorder(t->lchild);
postorder(t->rchild);
cout << t->data;
}
}
int main()
{
struct btnode *t;
cin >> s >> r;
length = strlen(s);
t = createbitree(0, 0, length);
postorder(t);
return 0;
}