PAT (Advanced Level)1020. Tree Traversals (25) 队列 二叉树的遍历

题目链接

//1020. Tree Traversals(25)

#include<cstdio>  
#include<iostream>  
#include<queue>  
using namespace std;

const int maxn = 1e3 + 10;
int n, a[maxn], b[maxn], ch[maxn][2], root;

void dfs(int&x, int l, int r, int ll, int rr)//关键在用ch二维数组记录根节点
{
	if (l > r) x = 0;//递归结束时,返回整棵树的树根
	for (int i = l; i <= r; i++)
	{
		if (a[i] == b[rr])
		{
			x = i;
			dfs(ch[x][0], l, i - 1, ll, ll + i - l - 1);//以x为根的左子树递归遍历。两边长度相等,左边(i-1-l+1),右边定下ll后,即可定。下同。
			dfs(ch[x][1], i + 1, r, ll + i - l, rr - 1);//以x为根的右子树递归遍历
		}
	}
}

int main()
{
	cin >> n;;
	for (int i = 1; i <= n; i++) cin >> b[i];//后序遍历
	for (int i = 1; i <= n; i++) cin >> a[i];//中序遍历
	dfs(root, 1, n, 1, n);
	queue<int> p; 
	p.push(root);
	//cout << root<<endl;
	while (!p.empty())
	{
		int q = p.front();  p.pop();
		if (root != q) cout << " ";
		cout << a[q];
		if (ch[q][0]) p.push(ch[q][0]);
		if (ch[q][1]) p.push(ch[q][1]);
	}
	cout << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值