重建二叉树的一般模板

中序先序转后序:

#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=100;
struct node
{
	int data;
	node* lchild;
	node* rchild;
};
int in[maxn],pre[maxn];
node* creat(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(pre[prel]==in[k])
		break;
	}
	root->lchild=creat(inl,k-1,prel+1,prel+k-inl);
	root->rchild=creat(k+1,inr,prel+k-inl+1,prer);
	return root;
}
void postorder(node* root)
{
	if(root==NULL)return;
	postorder(root->lchild);
	postorder(root->rchild);
	printf("%d\n",root->data);
}
int main()
{
	int n;
	cin>>n;
	for (int i=0;i<n;i++)
	{
		scanf("%d",&in[i]);
	}
	for (int i=0;i<n;i++)
	{
		scanf("%d",&pre[i]);
	}
	node* root=creat(0,n-1,0,n-1);
	postorder(root);
}

中序,后序转前序

#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=100;
struct node
{
	int data;
	node* lchild;
	node* rchild;
};
int in[maxn],pos[maxn];
node* creat(int inl,int inr,int posl,int posr)
{
	if(posl>posr)return NULL;
	node *root=new node;
	root->data=pos[posr];
	int k;
	for (k=inl;k<=inr;k++)
	{
		if(pos[posr]==in[k])
		break;
	}
	root->lchild=creat(inl,k-1,posl,posl+k-inl-1);
	root->rchild=creat(k+1,inr,posl+k-inl,posr-1);
	return root;
}
void preorder(node* root)
{
	if(root==NULL)return;
	printf("%d\n",root->data);
	preorder(root->lchild);
	preorder(root->rchild);
}
int main()
{
	int n;
	cin>>n;
	for (int i=0;i<n;i++)
	{
		scanf("%d",&pos[i]);
	}
	for (int i=0;i<n;i++)
	{
		scanf("%d",&in[i]);
	}
	node* root=creat(0,n-1,0,n-1);
	preorder(root);
}

中序,后序转层序

#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int maxn=100;
struct node
{
	int data;
	node* lchild;
	node* rchild;
};
int in[maxn],pos[maxn];
node* creat(int inl,int inr,int posl,int posr)
{
	if(posl>posr)return NULL;
	node *root=new node;
	root->data=pos[posr];
	int k;
	for (k=inl;k<=inr;k++)
	{
		if(pos[posr]==in[k])
		break;
	}
	root->lchild=creat(inl,k-1,posl,posl+k-inl-1);
	root->rchild=creat(k+1,inr,posl+k-inl,posr-1);
	return root;
}
int cnt=0,n;
void BFS(node* root)
{
	queue<node*> q;
	q.push(root);
	while(!q.empty())
	{
		node* temp=q.front();
		q.pop();
		printf("%d",temp->data);
		cnt++;
		if(cnt!=n)printf(" ");
		if(temp->lchild!=NULL) q.push(temp->lchild);
		if(temp->rchild!=NULL) q.push(temp->rchild);
 	}
}
int main()
{
	cin>>n;
	for (int i=0;i<n;i++)
	{
		scanf("%d",&pos[i]);
	}
	for (int i=0;i<n;i++)
	{
		scanf("%d",&in[i]);
	}
	node* root=creat(0,n-1,0,n-1);
	BFS(root);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值