树的遍历(PTA)

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

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

复制代码
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

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

void dfs(vector<vector<int>> &v, vector<int> postorder, vector<int> inorder, int k) {
	if (postorder.size() == 0) return;
	if (k == v.size()) v.push_back(vector<int>());
	int index = postorder.size() - 1;
	v[k].push_back(postorder[index]);
	int position = 0;
	while (inorder[position] != postorder[index]) position++;
	//cout << start_post << " ";
	vector<int> postorder_1;
	vector<int> inorder_1;
	for (int i = 0; i < position; i++) {
		postorder_1.push_back(postorder[i]);
		inorder_1.push_back(inorder[i]);
	}
	vector<int> postorder_2;
	for (int i = position; i < index; i++) {
		postorder_2.push_back(postorder[i]);
	}
	vector<int> inorder_2;
	for (int i = position + 1; i <= index; i++) {
		inorder_2.push_back(inorder[i]);
	}
	dfs(v, postorder_1, inorder_1, k + 1);
	dfs(v, postorder_2, inorder_2, k + 1);
	return;
}

int main() {
	vector<vector<int>> v;
	vector<int> v1, v2;
	int n;
	cin >> n;
	for (int i = 0, a; i < n; i++) {
		cin >> a;
		v1.push_back(a);
	}
	for (int i = 0, a; i < n; i++) {
		cin >> a;
		v2.push_back(a);
	}
	dfs(v, v1, v2, 0);
	int flag = 0;
	for (auto x : v) {
		for (auto y : x) {
			if (flag) cout << " ";
			cout << y;
			flag = 1;
		}
	}
	return 0;
}
相关推荐
智者知已应修善业8 分钟前
【51单片机0.1秒计时到21.0时点亮LED】2024-1-5
c++·经验分享·笔记·算法·51单片机
apcipot_rain11 分钟前
计科八股20260606——二叉树、PCA、图深度学习、进程上下文、C语言预编译、文件读写、单精度浮点数
c语言·数据结构·算法·pca·图神经网络
scx_link14 分钟前
逻辑回归的总结
算法·机器学习·逻辑回归
沐籽李27 分钟前
Proteina-Complexa:NVIDIA 如何把蛋白 Binder 设计推进到全原子生成时代?
大数据·人工智能·算法·英伟达·蛋白质生成
落羽的落羽36 分钟前
【项目】JsonRpc框架——开发实现2(业务层)
linux·数据结构·c++·人工智能·算法·json·动态规划
h_a_o777oah39 分钟前
2026 蓝桥杯软件 C++B组 国赛比赛经历及备赛建议
c++·经验分享·算法·蓝桥杯
SHARK_pssm41 分钟前
【数据结构——单链表】
数据结构·经验分享·笔记
lightqjx1 小时前
【算法】数据结构_并查集
数据结构·算法·并查集
小雨下雨的雨1 小时前
鸿蒙PC Electron框架实现流体气泡模拟器
前端·人工智能·算法·华为·electron·鸿蒙
txzrxz1 小时前
广度优先搜索详解(BFS)
算法·宽度优先