L2-011. 玩轉二叉樹

L2-011. 玩轉二叉樹

https://www.patest.cn/contests/gplt/L2-011

時間限制
400 ms
內存限制
65536 kB
代碼長度限制
8000 B
判題程序
Standard
作者
陳越

給定一棵二叉樹的中序遍歷和前序遍歷,請你先將樹做個鏡面反轉,再輸出反轉後的層序遍歷的序列。所謂鏡面反轉,是指將所有非葉結點的左右孩子對換。這裏假設鍵值都是互不相等的正整數。

輸入格式:

輸入第一行給出一個正整數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

#include <iostream>
#include <algorithm>
#include <cstring>
#include <functional>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;

typedef long long ll;
const int MAXN = 35;
int preOrder[MAXN];
int inOrder[MAXN];
vector<vector<int> >order(MAXN);//order[i]保存了層序遍歷中第i層的結果
void rebuild(int preL, int inL, int n, int c)
{
	if (n == 0)
		return;
	order[c].push_back(preOrder[preL]);
	if (n == 1)
		return;
	int i;
	for (i = 0; i < n; ++i)
		if (preOrder[preL] == inOrder[inL + i])
			break;
	rebuild(preL + i + 1, inL + i + 1, n - i - 1, c + 1);
	rebuild(preL + 1, inL, i, c + 1);
}

int main()
{
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n;
	while (cin >> n)
	{
		for (int i = 0; i < n; ++i)
			cin >> inOrder[i];
		for (int i = 0; i < n; ++i)
			cin >> preOrder[i];
		order.clear();
		order.resize(35);
		rebuild(0, 0, n, 1);
		bool flag = false;
		for (int i = 0; i <= 30; ++i)
		{
			if (order[i].size() == 0)
				continue;
			for (int j = 0; j < order[i].size(); ++j)
			{
				if (flag == false)
					flag = true;
				else
					cout << " ";
				cout << order[i][j];
			}
		}
		cout << endl;
	}


	return 0;
}





發佈了55 篇原創文章 · 獲贊 11 · 訪問量 7825
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章