#include<stdio.h>
#include<queue>
using namespace std;
//19-3-8
int i,N,pre[100005],in[100005];
struct node{
int data;
node* lchild;
node* rchild;
};
node* newNode(int x){
node* Node=new node;
Node->data=x;
Node->lchild=Node->rchild=NULL;
return Node;
}
void search(node* root,int x,int newdata){
if(root==NULL)
return;
if(root->data==x)
root->data=newdata;
search(root->lchild,x,newdata);
search(root->rchild,x,newdata);
}
void insert(node*&root,int x){
if(root==NULL){
root=newNode(x);
return;
}
if(root->data>x)
insert(root->lchild,x);
else
insert(root->rchild,x);
}
node* Create(int data[],int n){
node* root=NULL;
for(int i=0;i<n;i++)
insert(root,data[i]);
return root;
}
void LayerOrder(node* root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node* now=q.front();
q.pop();
printf("%d ",now->data);
if(now->lchild) q.push(now->lchild);
if(now->rchild) q.push(now->rchild);
}
}
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);
}
node* CreateTree(int preL,int preR,int inL,int inR){
if(preL>preR)
return NULL;
node* root=new node;
root->data=pre[preL];
int k;
for(k=inL;k<=inR;k++)
if(pre[preL]==in[k])
break;
int numLeft=k-inL;
root->lchild=CreateTree(preL+1,preL+numLeft,inL,k-1);
root->rchild=CreateTree(preL+numLeft+1,preR,k+1,inR);
return root;
}
int main(){
scanf("%d",&N);
printf("enter:\n");
for(i=0;i<N;i++)
scanf("%d",pre+i);
printf("enter:\n");
for(i=0;i<N;i++)
scanf("%d",in+i);
node* root=CreateTree(0,N-1,0,N-1);
printf("LayerOrder:\n");
LayerOrder(root);
printf("\nPostOrder:\n");
PostOrder(root);
printf("\nInOrder:\n");
InOrder(root);
printf("\nPreOrder:\n");
PreOrder(root);
return 0;
}
先序遍历+中序遍历->构建一棵树->对构建的树进行先序,中序,后序,层次遍历
最新推荐文章于 2022-10-27 20:28:32 发布