例如输入7
4 1 3 2 6 5 7
1 2 3 4 5 6 7
输出
4132657
1234567
2315764
4163572
#include<cstdio>
#define maxn 16
#include<algorithm>
#include<vector>
#include<cmath>
#include<iostream>
#include<queue>
using namespace std;
vector<int>preorder;
vector<int>inorder;
//利用前序序列和中序序列递归建树,递归边界是序列长度小于等于0,
//在递归程序中,输入序列左右两端点下标,先处理先序序列,得到序列对应树的根,然后处理中序序列,得到
//对应树的左子树右子树序列的左右端点下标,递归进行此过程,直到递归边界
struct node
{
int data;
node* lchild;
node* rchild;
};
node* build(int preL,int preR,int inL,int inR )
{
if(preL>preR){
return NULL;
}
node *root=new node;
root->data=preorder[preL];
root->lchild=NULL;
root->rchild=NULL;
int index;
for(index=inL;index<=inR;index++){
if(inorder[index]==preorder[preL]){
break;
}
}
root->lchild=build(preL+1,preL+index-inL,inL,index-1);//index-inL是前序序列左子树的长度
root->rchild=build(preL+index-inL+1,preR,index+1,inR);
return root;
}
node* create(int x)
{
node* Node=new node;
Node->data=x;
Node->lchild=NULL;
Node->rchild=NULL;
return Node;
}
void Find(node *root,int x,int newdata)
{
if(root==NULL)return ;
if(root->data==x){
root->data=newdata;
}
Find(root->lchild,x,newdata);
Find(root->rchild,x,newdata);
}
void Preorder(node * root)
{
if(root==NULL){
return;
}
printf("%d",root->data);
Preorder(root->lchild);
Preorder(root->rchild);
}
void Inorder(node *root)
{
if(root==NULL){
return ;
}
Inorder(root->lchild);
printf("%d",root->data);
Inorder(root->rchild);
}
void postorder(node *root)
{
if(root==NULL){
return ;
}
postorder(root->lchild);
postorder(root->rchild);
printf("%d",root->data);
}
void Layerorder(node *root)
{
if(root==NULL){
return ;
}
queue<node*>q1;
q1.push(root);
node *temp;
while(!q1.empty()){
temp=q1.front();
printf("%d",temp->data);
q1.pop();
if(temp->lchild!=NULL){
q1.push(temp->lchild);
}
if(temp->rchild!=NULL){
q1.push(temp->rchild);
}
}
}
int main()
{
int length;
scanf("%d",&length);
int temp;
for(int i=0;i<length;i++){
scanf("%d",&temp);
preorder.push_back(temp);
}
for(int i=0;i<length;i++){
scanf("%d",&temp);
inorder.push_back(temp);
}
node* root;
root=build(0,preorder.size()-1,0,inorder.size()-1);
Preorder(root);
printf("\n");
Inorder(root);
printf("\n");
postorder(root);
printf("\n");
Layerorder(root);
return 0;
}