1.已知前序和中序
node* pre_create(int prel,int prer,int inl,int inr)
{
if(prel>prer) return NULL;
node *root=new node;
root->data=pre[prel];
int temp;
for(int i=inl;i<=inr;i++)
{
if(in[i]==pre[0])
{
temp=i;
break;
}
}
root->lchild=pre_create(prel+1,prel+temp-inl,inl,temp-1);
root->rchild=pre_create(prel+temp-inl+1,prer,temp+1,inr);
return root;
}
2.已知后序与中序
node* post_create(int postl,int postr,int inl,int inr)
{
if(postl>postr) return NULL;
node *root=new node;
root->data=post[postr];
int temp;
for(int i=inl;i<=inr;i++)
{
if(in[i]==post[postr])
{
temp=i;
break;
}
}
root->lchild=post_create(postl,postl+temp-inl,inl,temp-1);
root->rchild=post_create(postl+temp-inl+1,prer-1,temp+1,inr);
return root;
}
3.已知层次与中序
//层次和中序序列构建二叉树:边输入数据边插入节点
void creat(node* &root,int val){
if(!root){
root=new node;
root->data=val;
root->lchild=root->rchild=NULL;
return;
}
//找到层次遍历该值在中序序列里的位置k
int k;
for(k=0;k<n;k++)
{
if(inorder[k]==val) break;
}
//找到根节点在中序序列里的位置
int u;
for(u=0;u<n;u++)
{
if(inorder[u]==root->data) break;
}
//要插入的节点是在根节点的右侧(右子树插入)
if(u<k) creat(root->rchild,val);
else creat(root->lchild,val);//左侧插入
}