PTA-L2-006 树的遍历 (25分)

PTA-L2-006 树的遍历 (25分)

传送门

给出后序遍历和中序遍历,给出层次遍历。

我们知道后序遍历:左右根
中序遍历:左根右

所以后序遍历的最后一个就是根节点,然后我们在中序遍历中找到这个根节点,把左子树和右子树区分开来,然后递归即可。
递归过程中我们把构建出来。
最后输出。
bfs输出即可。

代码部分:

#include <bits/stdc++.h>
#define mst(a, n) memset(a, n, sizeof(a))
using namespace std;
const int N = 1e3 + 10;
const int M = 55;
const int INF = 1e6 + 10;
typedef long long ll;

struct node
{
    
    
	int l;
	int r;
}f[N];
int mid[N];
int post[N];
int n;

int dfs(int midl, int midr, int posl, int posr)
{
    
    
	if (midl > midr)
	{
    
    
		return 0;
	}
	int root = post[posr];
	int fa = midl;
	while (root != mid[fa])
	{
    
    
		fa++;
	}
	int len = fa - midl;
	f[root].l = dfs(midl, fa - 1, posl, posl + len - 1);
	f[root].r = dfs(fa + 1, midr, posl + len, posr - 1);
	return root;
}

void bfs(int root)
{
    
    
	int a[N];
	int cnt = 0;
	queue<int> q;
	q.push(root);
	while (!q.empty())
	{
    
    
		int t = q.front();
		q.pop();
		if (t)
		{
    
    
			a[cnt++] = t;
		}
		if (f[t].l)
		{
    
    
			q.push(f[t].l);
		}
		if (f[t].r)
		{
    
    
			q.push(f[t].r);
		}
	}
	for (int i = 0; i < cnt; i++)
	{
    
    
		if (i)
		{
    
    
			cout << " ";
		}
		cout << a[i];
	}
	cout << endl;
}

int main()
{
    
    
	cin >> n;
	for (int i = 0; i < n; i++)
	{
    
    
		cin >> post[i];
	}
	for (int i = 0; i < n; i++)
	{
    
    
		cin >> mid[i];
	}
	int root = post[n - 1];
	dfs(0, n - 1, 0, n - 1);
	bfs(root);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_44624316/article/details/110148167