PAT 甲级 1020 Tree Traversals (25 分) 题解

一、原题及翻译
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

假设二叉树中的所有结点都是不同的正整数。给定后序和有序序列,请输入对应的二叉树层序序列。
Input Specification:
输入格式:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数N(≤30),即二叉树中节点的总数。第二行给出了后序序列,第三行给出了中序序列。每一行的所有数字都用空格分隔。

Output Specification:
输出格式:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

对于每个测试用例,在一行中打印相应二叉树的层序序列。所有数字由空格分开,结尾不能有多余空格。

Sample Input:
输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:
输出样例:

4 1 6 3 5 7 2

二、个人解析
题目描述很简单,就是给你中序和后序序列,让你写出层序序列。我的思路~~(别人的思路)~~ 比较简单,观察案例,在中序序列中,4前面是是的左子树,4的后面是4的右子树。那么如何确定左孩子呢?仔细观察,发现在后序序列中,从左往右数第三个,也就是左子树节点个数区间中最右边那个,就是4的左孩子,右孩子同理。具体实现思路看代码。

三、代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
int in[32];
int post[32];
struct node
{
	int val;
	node* l;
	node* r;
};
node* creat(int pl, int pr, int il, int ir)
{
	if (pl > pr)
		return NULL;
	node* np = new node;
	np->val = post[pr];
	int k = 0;
	for (int i = il; i <= ir; i++)//在il和ir这个区间里找和pr相等的节点
	{
		if (in[i] == post[pr])
		{
			k = i;
			break;
		}
	}
	int lnum = k - il;//左子树节点个数
	np->l = creat(pl, pl + lnum - 1, il, k-1);//在中序序列中il,k-1区间(当前节点左面)寻找,后序序列中pl,pl+lnum(后序序列前面那一部分)
	np->r = creat(pl+lnum, pr-1, k+1, ir);//在中序序列中k+1,ir区间(当前节点右面)寻找,后序序列中pl+lnum, pr-1(后序序列后面那一部分)
	return np;
}
void bfs(node * root)
{
	int flag = 0;
	queue<node*> que;
	que.push(root);
	while (!que.empty())
	{
		int n = que.size();
		for (int i = 0; i < n; i++)
		{
			node* np = que.front();
			if (flag == 1)
				cout << " ";
			flag = 1;
			cout << np->val;
			que.pop();
			if(np->l!=NULL)
			que.push(np->l);
			if(np->r!=NULL)
			que.push(np->r);
		}
	}
}
int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> post[i];
	}
	for (int i = 0; i < n; i++)
	{
		cin >> in[i];
	}
	node * root = creat(0, n-1, 0, n-1);
	bfs(root);
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值