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

二叉树的存储与遍历

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

存起来,一起用

相关推荐
旖旎夜光11 分钟前
list实现(7)(上)
c++
努力学算法的蒟蒻14 分钟前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
不会c嘎嘎21 分钟前
深入理解 C++ 异常机制:从原理到工程实践
开发语言·c++
崇山峻岭之间34 分钟前
C++ Prime Plus 学习笔记026
c++·笔记·学习
甄心爱学习1 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~2 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法
赖small强2 小时前
【Linux C/C++开发】Linux 平台 Stack Protector 机制深度解析
linux·c语言·c++·stack protector·stack-protector·金丝雀机制
Wild_Pointer.2 小时前
环境配置指南:全景目录
c++
AndrewHZ2 小时前
【遥感图像入门】DEM数据处理核心算法与Python实操指南
图像处理·python·算法·dem·高程数据·遥感图像·差值算法