给定中序遍历和任意遍历顺序还原一颗二叉树 (天梯赛L2-006)

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2

立个flag,要把树的大多经典题型全部写出来,努力!!!
这道题给定中序遍历和后序遍历还原一颗二叉树,然后用层次遍历遍历整棵树。事实上,只要给定你中序遍历提供左右子树,很关键),和任意遍历顺序(仅提供根节点)就可还原一颗二叉树,然后怎么样遍历就看题目要求了,对遍历有点迷茫的话可以看看我这篇文章(链接)

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int post[35], in[35];
vector<int> mytree;

struct binary_tree{
	int data;
	binary_tree* left;
	binary_tree* right;
};
typedef binary_tree* tree;

tree create(int postL, int postR, int inL, int inR){
	if(postL > postR){
		return NULL;
	}
	tree root = new binary_tree;
	root->data = post[postR];
	int k, numleft;
	for(k = inL; k <= inR; k++){
		if(in[k] == post[postR]){
			break;
		}
	}
	numleft = k - inL;
	root->left = create(postL, postL+numleft-1, inL, k-1);
	root->right = create(postL+numleft, postR-1, k+1, inR);
	return root;
}

void layer(tree root){
	queue<tree> q;
	q.push(root);
	while(!q.empty()){
		tree now = new binary_tree;
		now = q.front();
		q.pop();
		mytree.push_back(now->data);
		if(now->left != NULL) q.push(now->left);
		if(now->right != NULL) q.push(now->right);
	}
}

int main(){
	int n, i;
	cin >> n;
	for(i = 1; i <= n; i++){
		cin >> post[i];
	}
	for(i = 1; i <= n; i++){
		cin >> in[i];
	}
	tree root = create(1, n, 1, n);
	layer(root);
	cout << mytree[0];
	for(i = 1; i < mytree.size(); i++){
		cout << " " << mytree[i];
	}
}

其实要注意的是,也是我踩过的坑,在下列代码中,每次我们要准确的确定每个序列的左子树的区间和右子树的区间(建议画图,避免出错)

root->left = create(postL, postL+numleft-1, inL, k-1);
root->right = create(postL+numleft, postR-1, k+1, inR);

很直观
完成!!!(天梯赛25分到手)
下一个博客:判断一棵树是否是完全二叉树(maybe)
再见,我们下次见!!!

猛兽总是独行,只有牛羊才成群结队。
做好自己就行了!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值