PAT甲级 1020 Tree Traversals (25分)

1020 Tree Traversals (25分)

题目链接:PAT A 1020
在这里插入图片描述

题目大意:给出一棵树的后序遍历和中序遍历,要求求出该树的层序遍历。

思路分析:根据后序遍历和中序遍历可以构建出唯一的一颗二叉树,用到了递归的求解方法。对于每一棵树,后序遍历的最后一个元素就是该树的根节点,然后在中序遍历中找到这个元素,记录对应的下标,左面的元素就是这棵树的左子树,右面的树就是这棵树的右子树,然后递归求解,重复上述过程,就可以构建出唯一的一颗二叉树,最后直接进行层序遍历即可~

ps:如果你对递归感觉很懵,理解的不透彻,可以先把参考代码拷贝到编译器中,然后用调试的方法跟踪执行,看看具体是怎样的执行的,用笔在纸上将完整的过程推导一遍,反复理解。递归的理解需要一个过程,坚持下来肯定会有收获的!

AC代码:

#include<iostream>
#include<queue>
using namespace std;
struct node{
	int data;
	node* lchild;
	node* rchild;
};
int n, postorder[35], inorder[35]; //后序遍历和中序遍历数组 
node* create(int postl, int postr, int inl, int inr) {
	if(postl > postr) //递归返回条件 
		return NULL;
	node* root = new node;
	root->data = postorder[postr];
	int k;
	for(k = inl; k <= inr; k++) { //在中序遍历中查找根节点的索引 
		if(inorder[k] == postorder[postr])
			break;
	}
	int numleft = k - inl; //左子树的数目 
	root->lchild = create(postl, postl + numleft - 1, inl, k - 1); //递归建树 
	root->rchild = create(postl + numleft, postr - 1, k + 1, inr);
	return root;
}
void layerorder(node* root) { //层序遍历 
	queue<node*> q;
	q.push(root);
	int cnt = 0; //记录输出空格用 
	while(q.empty() != true) {
		node* now = q.front();
		q.pop();
		cout << now->data;
		cnt++;
		if(cnt != n)
			cout << " ";
		if(now->lchild != NULL) 
			q.push(now->lchild);
		if(now->rchild != NULL) 
			q.push(now->rchild);
	}
}
int main() {
	cin >> n;
	for(int i = 0; i < n; i++)
		cin >> postorder[i];
	for(int i = 0; i < n; i++)
		cin >> inorder[i];
	node* root = create(0, n - 1, 0, n - 1);
	layerorder(root);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值