L2-006 树的遍历 (25分) 自我总结

有空再更新
题目链接

AC代码

#include <bits/stdc++.h>
using namespace std;
const int N = 39;
int Post[N],In[N];
struct node
{
	int lson,rson;
}tr[N]; 
//中序数组的左右边界和后序数组的左右边界 
int dfs(int lIn,int rIn,int lPost,int rPost)
{
	
	if(lIn>rIn) return 0;
	int root = Post[rPost];//后序数组中的最后一个是根节点
	int i=lIn;
	while(In[i]!=root) i++;
	int len = i - lIn;
//	cout<<lIn<<" "<<i-1<<endl; 
	tr[root].lson = dfs(lIn,i-1,lPost,lPost+len-1);
	tr[root].rson = dfs(i+1,rIn,lPost+len,rPost-1);
	return root;	
}
void bfs(int x)
{
	queue<int> q;
	q.push(x);
	int ans[100];
	int t = 0;
	while(!q.empty())
	{
		int tmp = q.front();
		q.pop();
	    if(tmp!=0) ans[t++] = tmp;
		if(tr[tmp].lson) q.push(tr[tmp].lson);
		if(tr[tmp].rson) q.push(tr[tmp].rson);
	}
	for(int i=0;i<t;i++)
	{
		cout<<ans[i];
		if(i<t-1) cout<<" "; 
	}
}
int main(){
	int n;
	cin>>n;
	for(int i=1;i<=n;i++) scanf("%d",&Post[i]);
	for(int i=1;i<=n;i++) scanf("%d",&In[i]);

	dfs(1,n,1,n);
	//cout<<"wa"<<endl; 
	bfs(Post[n]);
	return 0;
}

posted @   翔村亲亲鸟  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示