PAT1020 Tree Traversals (25)(中序后序遍历生成树)

题目很简单,就是给出树的中序和后序遍历,要求输出层序遍历,记录一下主要是因为之前这块一直懒得写,一直没写过

#include<bits/stdc++.h>
#define INF 0x6ffff
using namespace std;

struct node {
	int data;
	node *left, *right;
};
int n;
int postOrder[35],inOrder[35];

node* buildTree(int l, int r, int ll, int rr){
	if (l > r || ll > rr) {
		return nullptr;
	}
	node *temp = new node;
	int d = postOrder[r];
	int pos;
	for (int i = ll; i <= rr; i++) {
		if (d == inOrder[i]) {
			pos = i;
			break;
		}
	}	
	int numLeft = pos - ll;
	int numRight = rr - pos;
	temp->data = d;
	temp->left = buildTree(l, l + numLeft - 1, ll, pos - 1);
	temp->right = buildTree(r - numRight, r-1, pos + 1, rr);
	return temp;
}

void printTree(node *front) {
	queue<node*> q;
	q.push(front);
	while (!q.empty()) {
		node *t = q.front(); q.pop();
		if (!t) continue;
		if (t == front)
			printf("%d", t->data);
		else
			printf(" %d", t->data);
		q.push(t->left);
		q.push(t->right);
	}
}

int main() {
	cin >> n;
	for (int i = 1; i <= n; i++)
		cin >> postOrder[i];
	for (int i = 1; i <= n; i++)
		cin >> inOrder[i];
	node *front = buildTree(1, n, 1, n);
	printTree(front);
	return 0;
}

 

 

 

转载于:https://www.cnblogs.com/seasonal/p/10343636.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值