天梯赛&&HBU训练营——玩转二叉树 (25分)

给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

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

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

输入样例:

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

输出样例:

4 6 1 7 5 3 2

你永远不知道我这道题改了多少遍,找了多少次错,(我都没记,你还能知道?)最后发现,本应先输入中序,再输入前序,我恰好相反。。。改了很多,就差把main都改了,结果。。。。

分析:镜面反转二叉树,两种思路,一种是真的反转,就是交换左右子树(这个我也写了,后来不小心给删了),一种就是先遍历右子树,再遍历左子树。层次遍历,还是采用队列(不用自己写个队列真舒服)
#include <iostream>
#include <cstdlib>
#include <queue>
using namespace std; 

typedef struct Node{
	int data;
	struct Node *left,*right;
}Node,*Tree;

Tree create(int n,int *pre,int *mid){
	if(n==0)
		return NULL;
	Tree tree = (Node *)malloc(sizeof(Node));
	tree->data = pre[0];
	tree->left = tree->right = NULL;
	int i;
	for(i = 0;i<n;i++){
		if(mid[i]==pre[0])
			break;
	}
	tree->left = create(i,pre+1,mid);
	tree->right = create(n-i-1,pre+i+1,mid+i+1);
	return tree;
}

void order(int n,Tree tree){
	if(!tree)
		return;
	queue<Tree> q;
	q.push(tree);
	int len = 0;
	while(!q.empty()){
		Tree t = q.front();
		len++;
		if(len<n)
			cout << t->data << " ";
		else
			cout << t->data;
		q.pop();
		if(t->right)
			q.push(t->right);
		if(t->left)
			q.push(t->left);
	}
}

int main(){
	ios::sync_with_stdio(false);
	int n;
	cin >> n;
	int pre[n],mid[n];
	for(int i = 0;i<n;i++){
		cin >> mid[i];
	}
	for(int i = 0;i<n;i++){
		cin >> pre[i];
	}
	Tree tree = create(n,pre,mid);
	order(n,tree);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45845039/article/details/107763054