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

二叉树的存储与遍历

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

存起来,一起用

相关推荐
Ethon_王2 分钟前
C++ STL deque容器详解
c++
Cosolar4 分钟前
MCP技术应用全景:连接智能世界的万能接口
后端·算法
前端 贾公子12 分钟前
力扣349 == 两个数组交集的两种解法
算法
ZHW_AI课题组12 分钟前
使用SVM对心脏数据是否患病进行分类预测
算法·支持向量机·分类
梦の20 分钟前
C++Cherno 学习笔记day20 [81]-[85] 可视化基准测试、单例模式、小字符串优化sso、跟踪内存分配、左值与右值
c++·笔记·学习
硬匠的博客35 分钟前
C/C++指针
c语言·开发语言·c++
向日葵.1 小时前
CMake学习
开发语言·c++·学习
wuqingshun3141591 小时前
蓝桥杯 1.路径之谜
c++·算法·职场和发展·蓝桥杯·深度优先
Vesan,1 小时前
C++ static的使用方法及不同作用
java·jvm·c++
巴巴_羊2 小时前
Layout 路由
数据结构