通过后序和中序的序列来构建这棵树,然后输出层序序列。
思路都是一样的。递归的思想。后序的最后一个点就是根节点,然后就在中序中去寻找该节点。则左边为左子树中序,右边为右子树中序。
一开始用数组去实现的递归,不知为何总是崩溃。于是照着别人的代码敲了一遍。其中的bfs还是要掌握的。
还有就是递归的时候要给节点赋予实体。
把Tree *tree= (Tree *)malloc(sizeof(Tree));
写成Tree *tree;
是不对的。程序会崩溃,跑不了。因为你不给他分配有空间的实体的话,这个树是不存在的,其中的tree也只是一个形参,即便你赋值了程序结束后就不存在,只有用malloc把他变成实参。
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
typedef struct Tree{
int data;
Tree *left;
Tree *right;
}Tree;
int pos[33],in[33];
Tree *buildtree(int pl,int pr,int il,int ir)
{
if(pl>pr)
return NULL;
int p=il;
while(in[p]!=pos[pr])
p++;
Tree *tree= (Tree *)malloc(sizeof(Tree));
tree->data=in[p];
tree->left=buildtree(pl,pr-ir+p-1,il,p-1);
tree->right=buildtree(pr-ir+p,pr-1,p+1,ir);
return tree;
}
void printLevelOrder(Tree *root)
{
Tree *tr;
tr=NULL;
bool flag=false;
queue<Tree *> que;
que.push(root);
while(!que.empty())
{
tr=(Tree *)que.front();
que.pop();
if(tr==NULL)
continue;
if(!flag)
{
printf("%d",tr->data);
flag=true;
}
else
{
printf(" %d",tr->data);
}
que.push(tr->left);
que.push(tr->right);
}
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&pos[i]);
for(i=0;i<n;i++)
scanf("%d",&in[i]);
Tree* lol=buildtree(0,n-1,0,n-1);
printLevelOrder(lol);
return 0;
}