【算法】二叉树的存储与遍历模板

二叉树的存储与遍历

cpp 复制代码
const int N = 1e6 + 10;

// 二叉树的存储,l数组为左节点,r数组为右结点
int l[N], r[N];
// 存储节点的数据
char w[N];
// 节点的下标指针
int idx = 0;

// 先序创建
int pre_create(int n) {
	cin >> w[n];
	if (w[n] == '#') return -1;
	l[n] = pre_create(++idx);
	r[n] = pre_create(++idx);
	return n;
}

// 中序创建
int in_create(int n) {
	if (w[n] == '#') return -1;
	l[n] = in_create(++idx);
	cin >> w[n];
	r[n] = in_create(++idx);
	return n;
}

// 后序创建
int back_create(int n) {
	if (w[n] == '#') return -1;
	l[n] = back_create(++idx);
	r[n] = back_create(++idx);
	cin >> w[n];
	return n;
}

// 先序遍历
void pre_print(int n){
	if (w[n] != '#') cout << w[n] << ' ';
	if (l[n] > 0) pre_print(l[n]);
	if (r[n] > 0) pre_print(r[n]);
}

// 中序遍历
void in_print(int n){
	if (l[n] > 0) in_print(l[n]);
	if (w[n] != '#') cout << w[n] << ' ';
	if (r[n] > 0) in_print(r[n]);
}

// 后序遍历
void back_print(int n){
	if (l[n] > 0) back_print(l[n]);
	if (r[n] > 0) back_print(r[n]);
	if (w[n] != '#') cout << w[n] << ' ';
}

// 层序遍历
void bfs(int root){
	queue<int> que;
	que.push(root);
	while (!que.empty()) {
		int t = que.front();
		cout << w[t] << ' ';
		que.pop();
		if (l[t] > 0 && w[l[t]] != '#')
			que.push(l[t]);
		if (r[t] > 0 && w[r[t]] != '#')
			que.push(r[t]);
	}
}

应用

cpp 复制代码
int main(){
    // 先序创建
    pre_create(++idx);
    // 中序创建
    // in_create(++idx);
    // 后序创建
    // back_create(++idx);
    // 先序遍历
	pre_print(1);
	// 中序遍历
	in_print(1);
	// 后序遍历
	back_print(1);
	// 层序遍历
	bfs(1);
    // 测试数据abc##de#g##f###
    // 输出如下:
    // a b c d e g f 
    // c b e g d f a 
    // c g e f d b a 
    // a b c d e f g 
    return 0;
}

存起来,一起用

相关推荐
小蒋学算法18 分钟前
算法-删除元素后最大固定点数目-典型最长增长序列算法
数据结构·算法
RD_daoyi22 分钟前
Google偷偷给AI引用加了五个新功能:内联引用、悬停预览、品牌展示……但点击率真的回来了吗?
大数据·网络·人工智能·算法·安全·搜索引擎
船漏了就会沉31 分钟前
后缀自动机(SAM):字符串处理的“万能瑞士军刀”
算法
醉城夜风~42 分钟前
C++模板详解:从基础到高级全面解析
java·开发语言·c++
RuiZN1 小时前
Muduo---Channel类
运维·服务器·c++
誰能久伴不乏1 小时前
深入理解 C++ 多态:对象模型与底层机制解析
开发语言·c++·架构
ShineWinsu1 小时前
对于Linux:自定义协议(基于TCP)实现网络计算器的解析
linux·网络·c++·网络协议·tcp/ip·面试·网络计算器
郝学胜-神的一滴1 小时前
中级OpenGL教程 026:Assimp库从编译到实战全攻略
c++·unity·游戏引擎·图形渲染·unreal engine·opengl
今夜有雨.1 小时前
C++JSON 解析器
c++·笔记·后端·学习·json
白白白小纯2 小时前
算法篇—链表的中间节点
c语言·数据结构·算法·leetcode