内容:
先序遍历、中序遍历,后序遍历,层次遍历
先序+中序构建二叉树
后序+中序构建二叉树
层次+中序构建二叉树
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
int data;
node * lchild;
node * rchild;
};
node * pre_in(int inL,int inR,int preL,int preR)
{
if(preL>preR)
return NULL;
node *root=new node;
root->data=pre[preL];
int k;
for(k=inL;k<=inR;++k)
{
if(in[k]==pre[preL])
break;
}
int numLeft=k-inL;
root->lchild=create(inL,k-1,preL+1,preL+numleft);
root->rchild=create(k+1,inR,preL+numleft+1,preR);
return root;
}
node * post_in(int inL,int inR,int postL,int postR)
{
if(postL>postR)
return NULL;
node *root=new node;
root->data=post[postR];
int k;
for(k=inL;k<=inR;++k)
{
if(in[k]==post[postR])
break;
}
int numLeft=k-inL;
root->lchild=create(inL,k-1,postL,postL+numleft-1);
root->rchild=create(k+1,inR,postL+numleft,postR-1);
return root;
}
int in[30],level[30],flag[30],post[30],pre[30],n;
node * level_in()
{
int index=0;
queue<node *> q;
node * root=new node;
root->data=level[index];
root->lchild=NULL;
root->rchild=NULL;
index++;
q.push(root);
node * temp;
while(!q.empty())
{
temp=q.front();
q.pop();
int i;
for(i=0;i<n;++i)
if(temp->data==in[i])
break;
flag[i]=1;
if(flag[i-1]!=1&&i>0)
{
node *t=new node;
t->data=level[index];
t->lchild=NULL;
t->rchild=NULL;
temp->lchild=t;
index++;
q.push(t);
}
if(flag[i+1]!=1&&i<n-1)
{
node *t=new node;
t->data=level[index];
t->lchild=NULL;
t->rchild=NULL;
temp->rchild=t;
index++;
q.push(t);
}
}
return root;
}
void pre(node * p)
{
if(p==NULL)
return ;
printf("%d ",p->data);
pre(p->lchild);
pre(p->rchild);
}
void in(node * p)
{
if(p==NULL)
return ;
pre(p->lchild);
printf("%d ",p->data);
pre(p->rchild);
}
void post(node * p)
{
if(p==NULL)
return ;
pre(p->lchild);
pre(p->rchild);
printf("%d ",p->data);
}
void layer(node * root)
{
queue<node *> q;
q.push(root);
node *temp;
while(!q.empty())
{
temp=q.front();
printf("%d ",temp->data);
q.pop();
if(temp->lchild!=NULL)
q.push(temp->lchild);
if(temp->rchild!=NULL)
q.push(temp->rchild);
}
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&level[i]);
for(int i=0;i<n;i++)
scanf("%d",&in[i]);
memset(flag,0,sizeof(flag));
node * root=level_in();
pre(root);
return 0;
}