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

二叉树的存储与遍历

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 小时前
2026年6月GESP真题及题解(C++一级):交税
c++·题解·真题·gesp·一级·2026年6月·交税
Jerry4 小时前
LeetCode 160. 相交链表
算法
Jerry5 小时前
LeetCode 19. 删除链表的倒数第 N 个结点
算法
金銀銅鐵5 小时前
费马小定理
python·数学·算法
技术不好的崎鸣同学6 小时前
[ACTF2020 新生赛]Exec 思路及解法
算法·安全·web安全
Full Stack Developme7 小时前
Java LRU 与 LFU 算法及应用
java·开发语言·算法
Jerry9 小时前
LeetCode 707. 设计链表
算法
疋瓞9 小时前
python和C++对比(1)_数据类型和数据结构
数据结构·c++·python
C语言小火车9 小时前
C++ 堆排序深度精讲:基于完全二叉树的选择排序进化,最坏情况 O(n log n) 的稳定王者
开发语言·c++·算法·排序算法·堆排序