在我心里只要是二叉树就一定与递归有千丝万缕的关系,因此先递归建立左子树,再递归右子树,
像递归这种东西,一定要站在一个高度去看他,如果想的太复杂了会越陷越深,所以写代码是只要
给他一个宏观上的指令,就可以了。层序遍历吧,代码很简单,看一遍应该就理解了。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <cstdlib>
using namespace std;
int mid[100],post[100],pre[100];
int n;
struct node
{
int c;
node *lchild,*rchild;
};
//根据后序遍历与中序遍历递归建树
node *postMidCreatTree(int len, int *mid, int *post)
{
int i;
if(len<=0)
return NULL;
node *p = (node *)malloc(sizeof(node));
p->lchild = p-> rchild = NULL;
p->c = post[len-1];
for(i=0; i<n; ++i)
if(mid[i] == post[len-1])
break;
int l=i;
p->lchild = postMidCreatTree(l,mid,post);
p->rchild = postMidCreatTree(len-l-1,mid+l+1,post+l);
return p;
}
//层序遍历
int levelTraverseTree(node *head)
{
queue<node *>q;
q.push(head);
int i=0;
while(!q.empty())
{
node *t;
t = q.front();
q.pop();
pre[i++] = t->c;
if(t->lchild)
q.push(t->lchild);
if(t->rchild)
q.push(t->rchild);
}
return i;
}
int main()
{
cin >> n;
for(int i=0; i<n; ++i)
cin >> post[i];
for(int i=0; i<n; ++i)
cin >> mid[i];
node *head = (node *)malloc(sizeof(node));
head->lchild = head->rchild = NULL;
head = postMidCreatTree(n,mid,post);
int len = levelTraverseTree(head);
for(int i=0; i<len-1; ++i)
cout << pre[i] << " ";
cout << pre[len-1] << endl;
return 0;
}