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

二叉树的存储与遍历

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;
}

存起来,一起用

相关推荐
指令集梦境4 分钟前
图解:单调栈算法模板(Java语言)
java·开发语言·算法
小灰灰搞电子12 分钟前
C++ boost::circular_buffer 详解:原理、用法与实战
开发语言·c++·boost
生成论实验室26 分钟前
自动驾驶:一个自主运动的系统
人工智能·算法·机器学习·语言模型·机器人·自动驾驶·安全架构
sheeta199828 分钟前
LeetCode 每日一题笔记 日期:2026.06.16 题目:3612. 字符串特殊符号处理
笔记·算法·leetcode
CoderYanger31 分钟前
A.每日一题:2095. 删除链表的中间节点
java·数据结构·程序人生·leetcode·链表·面试·职场和发展
青山木36 分钟前
Hot 100 --- 矩阵置零
线性代数·算法·leetcode·矩阵·哈希算法
Jasmine_llq37 分钟前
《B4264 [GESP202503 四级] 二阶矩阵》
线性代数·算法·矩阵·二维矩阵遍历枚举所有2×2矩阵·交叉乘积等式条件判断·输入输出快读加速·长整型防溢出计数统计
星恒随风40 分钟前
C++ string 类详解:常用接口、OJ 场景与模拟实现中的深浅拷贝
开发语言·c++·笔记·学习·状态模式
不知名的老吴1 小时前
面经经验分享|算法和数据结构考察
数据结构·经验分享·算法
程序喵大人1 小时前
【C++并发系列】第二章:锁解决了什么问题?
开发语言·c++·并发编程·