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;
}

猜你喜欢

转载自blog.csdn.net/qq_45769627/article/details/110250516