构建二叉树
- 前序遍历,后序遍历,层次遍历都是提供根结点的信息,中序遍历用来区分左右子树。
- 中序遍历和前,中,层次任一组合都可以完全确定一颗二叉树,无中序遍历一定无法唯一确定一颗二叉树。
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
int n;
struct node{
int data;
node *lchild,*rchild;
};
int post[35],in[35];
node* build(int posts,int poste,int ins,int ine){
if(posts>poste)return NULL;
int k;
for(k=ins;k<=ine;k++)
if(post[poste]==in[k])
break;
node* root=new node;
root->data=post[poste];
int numleft=k-ins;
root->lchild=build(posts,posts+numleft-1,ins,k-1);
root->rchild=build(posts+numleft,poste-1,k+1,ine);
return root;
}
queue<node*> que;
void print(node* root){
if(root)que.push(root);
else return;
bool f=0;
while(!que.empty()){
node* temp=que.front();que.pop();
if(f)cout<<" ";
cout<<temp->data;f=1;
if(temp->lchild)
que.push(temp->lchild);
if(temp->rchild)
que.push(temp->rchild);
}
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++)scanf("%d",&post[i]);
for(int i=0;i<n;i++)scanf("%d",&in[i]);
node* root=build(0,n-1,0,n-1);
print(root);
}