当前位置: 首页 > news >正文

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

二叉树的存储与遍历

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

应用

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

存起来,一起用

http://www.lryc.cn/news/238893.html

相关文章:

  • 【Go学习之 go mod】gomod小白入门,在github上发布自己的项目(项目初始化、项目发布、项目版本升级等)
  • 79基于matlab的大米粒中杂质识别
  • Vue 项目实战——如何在页面中展示 PDF 文件以及 PDFObject 插件实战
  • 系列六、ThreadLocal内存泄露案例
  • Java学习笔记44——Stream流
  • excel表格忘记密码,如何找回?
  • IDEA版SSM入门到实战(Maven+MyBatis+Spring+SpringMVC) -Mybatis初识和框架搭建
  • 差分放大器工作原理(差分放大器和功率放大器区别)
  • SystemV
  • LiteOS同步实验(实现生产者-消费者问题)
  • redis的性能管理和雪崩
  • python:关于函数内 * 和 / 是什么意思?
  • PPT密码解密,简单教程,保护幻灯片内容
  • Apache Airflow (十一) :HiveOperator及调度HQL
  • SpringBoot-Docker容器化部署发布
  • 重生奇迹mu格斗怎么加点
  • 「浙江科聪新品发布」新品发布潜伏顶升式移动机器人专用控制器
  • 大数据学习(22)-spark
  • String类常用方法总结
  • TensorFlow实战教程(二十八)-Keras实现BiLSTM微博情感分类和LDA主题挖掘分析
  • 个人博客添加访问人数以及访问时间-githubpage
  • Django--重定向redirect
  • 在html和css中的引用svg(一)
  • C/C++ 实现:自然排序:针对两个需要排序的字符串,不仅逐个比较每个字符的顺序,对于连在一起的数字字符会作为一个完整数字进行比较 某知名企业的笔试题
  • sse实时通信
  • Qt专栏3—Qt项目创建Hello World
  • linux输出的重定向无效问题和解决
  • chromium114添加新的语言国际化支持
  • 赛氪荣幸受邀参与中国联合国采购促进会第五次会员代表大会
  • 车载通信架构 —— 传统车内通信网络发展回顾