当前位置: 首页 > 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.hskmm.com/?act=detail&tid=36083

相关文章:

  • 做了一个概率小游戏,没想到服务器被打爆被攻击了!原因竟然是他?真没想到...
  • 接下来的目标
  • 阿里云对象存储OSS之Java - Soul
  • 敬启,致那时的我
  • 后量子密码学技术与标准化进程解析
  • 10月21日
  • 清楚标签默认样式,内容溢出盒子时的处理
  • 用 大模型 和 Gradio 构建一个 AI 反向词典
  • MySQL 事务
  • python概念详解
  • JAVA基础理解
  • 1279. 红绿灯路口
  • 软件工程第三次作业
  • 用户消费行为数据分析(随笔)
  • linux常用命令总结
  • sqlserver 主要的日期函数及用法示例
  • ICPC2022沈阳 游记(VP)
  • 大数据分析基础及应用案例:第四周学习报告——线性回归模型
  • 「LG7446-rfplca」题解
  • 图论刷题记录
  • 「LG6596-How Many of Them」题解
  • 骗我呢
  • 手写体识别
  • 你好,我是肆闲:C语言的学习,成长与分享旅程
  • AGC 合集 1.0
  • 20231302邱之钊密码系统设计实验一第二
  • 深入BERT内核:用数学解密掩码语言模型的工作原理
  • ZR 2025 NOIP 二十连测 Day 6
  • 20251021
  • [论文笔记] Precision-Guided Context Sensitivity for Pointer Analysis