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

二叉树的中序遍历- 二叉树基本-递归 - MKT

image

 

image

 

image

 

image

 

#include <iostream>
#include <queue>
using namespace std;struct TreeNode {int val;TreeNode* left;TreeNode* right;TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};// 创建二叉树
TreeNode* createBinaryTree() {TreeNode* root = new TreeNode(1);root->left = new TreeNode(2);root->right = new TreeNode(3);root->left->left = new TreeNode(4);root->left->right = new TreeNode(5);return root;
}// 前序遍历
void preorder(TreeNode* root) {if (root == nullptr) return;cout << root->val << " ";preorder(root->left);preorder(root->right);
}// 中序遍历
void inorder(TreeNode* root) {if (root == nullptr) return;inorder(root->left);cout << root->val << " ";inorder(root->right);
}// 后序遍历
void postorder(TreeNode* root) {if (root == nullptr) return;postorder(root->left);postorder(root->right);cout << root->val << " ";
}// 层次遍历
void levelOrder(TreeNode* root) {if (root == nullptr) return;queue<TreeNode*> q;q.push(root);while (!q.empty()) {TreeNode* current = q.front();q.pop();cout << current->val << " ";if (current->left != nullptr) q.push(current->left);if (current->right != nullptr) q.push(current->right);}
}// 计算树高
int height(TreeNode* root) {if (root == nullptr) return 0;return max(height(root->left), height(root->right)) + 1;
}// 计算节点数
int countNodes(TreeNode* root) {if (root == nullptr) return 0;return 1 + countNodes(root->left) + countNodes(root->right);
}int main() {TreeNode* root = createBinaryTree();cout << "前序遍历: ";preorder(root);cout << endl;cout << "中序遍历: ";inorder(root);cout << endl;cout << "后序遍历: ";postorder(root);cout << endl;cout << "层次遍历: ";levelOrder(root);cout << endl;cout << "树高: " << height(root) << endl;cout << "节点数: " << countNodes(root) << endl;return 0;
}

  

http://www.gsyq.cn/news/26711.html

相关文章:

  • 构建YouTube视频总结摘要智能体
  • 后量子密码学技术与标准化进程解析
  • JAVA基础理解
  • ICPC2022沈阳 游记(VP)
  • 大数据分析基础及应用案例:第四周学习报告——线性回归模型
  • 「LG7446-rfplca」题解
  • 手写体识别
  • 20231302邱之钊密码系统设计实验一第二
  • 你好,我是肆闲:C语言的学习,成长与分享旅程
  • ZR 2025 NOIP 二十连测 Day 6
  • 20251021
  • ORA-600 kokasgi1故障处理(sys被重命名)---惜分飞
  • 简单页面聊天
  • python 包来源镜像
  • CSharp基础复习-1
  • 米理 课程描述/学习计划/Study program
  • png隐写文件与文件占用
  • Windows和Linux设置Https(SSL)访问 - 详解
  • 完整教程:罗技G102有线鼠标自己维修教程
  • 挖矿-学校挖矿排查
  • Spring 统一机制处理 - 拦截器与适配器
  • 如何将海量纸质表格一键数字化?表格识别技术给出答案
  • 10.21 NOIP 模拟赛 T1. 小 h 学步
  • 实用指南:免费html网页模板 html5网站模板 静态网页模板
  • 远程服务器显示pyQt界面
  • 软工第三次作业--结对作业
  • 原来用聊天记录就可以创造数字分身!WeClone项目在Lab4AI平台上的复现
  • Day1HTML的基本骨架
  • 结对项目作业
  • C语言项目开发常用目录结构 - Invinc