PAT A1020 Tree Traversals(已知二叉树后序/中序,求层序)

原题:https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072
题目要求很简单,就是已知二叉树后序/中序,求层序
我首先重建了这颗二叉树,然后进行层序遍历。
我熟悉了二叉树的指针操作,还有就是建议做题之前自己在纸上模拟一下:
在这里插入图片描述

#include <iostream>
#include <string>
#include <set>
#include <map>
#include<queue>
#include<stack>
#include<algorithm>

//new and delete
//A1020 Tree Traversals
using namespace std;


const int MaxN = 40;
typedef int ElemType;
struct node {
	ElemType v;
	node* lchild;
	node* rchild;
};

int post[MaxN],in[MaxN];	//后序(左右根)、中序(左根右)遍历

//当前后序遍历[postL, postR], 当前中序遍历[inL, inR],返回根节点地址
node* create_po_in(int postL, int postR, int inL, int inR) {
	//退出条件
	if (postL > postR)
		return NULL;

	int root1 = post[postR];
	//寻找in[k]=root1
	int k = -1;	
	for (k = inL; k <= inR; k++) {
		if (in[k] == root1)
			break;
	}
	if (k == -1) {
		cout << "error!" << endl;
		return NULL;
	}

	node* root=new node;
	root->v = root1;
	root->lchild = create_po_in(postL, postL + k - 1-inL, inL, k - 1);
	root->rchild = create_po_in(postL + k-inL, postR - 1, k + 1, inR);
	return root;
}
//层序遍历
void LevelOrder(node* root,int N) {
	queue<node*>q;
	q.push(root);
	
	int index=0;
	while (!q.empty()) {
		//访问队首元素
		node* temp = q.front();
		cout << temp->v;
		index++;
		if (index < N)
			cout << " ";
		else
			cout << endl;
		q.pop();
		//左右孩子入队
		if(temp->lchild)
			q.push(temp->lchild);
		if (temp->rchild)
			q.push(temp->rchild);

	}

	return;
}

int main() {
	int N;	//The number of node
	cin >> N;
	
	for (int j = 0; j < N; j++) {
		cin >> post[j];
	}
	for (int j = 0; j < N; j++) {
		cin >> in[j];
	}

	node* root = create_po_in(0, N - 1, 0, N - 1);
	LevelOrder(root,N);

	return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值