代码分析#include <iostream> #include <queue> #include <stack> #include <string> using namespace std; struct Student { string name; int number; int score; }; struct TreeNode { Student data; TreeNode* left; TreeNode* right; TreeNode(Student s) : data(s), left(nullptr), right(nullptr) {} }; void postOrder(TreeNode* root) { if (!root) return; postOrder(root->left); postOrder(root->right); cout << root->data.name << " " << root->data.number << " " << root->data.score << endl; } void preOrder(TreeNode* root) { stack<TreeNode*> s; s.push(root); while (!s.empty()) { TreeNode* node = s.top(); s.pop(); if (node) { cout << node->data.name << " " << node->data.number << " " << node->data.score << endl; s.push(node->right); s.push(node->left); } } } void levelOrder(TreeNode* root) { queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* node = q.front(); q.pop(); if (node) { cout << node->data.name << " " << node->data.number << " " << node->data.score << endl; q.push(node->left); q.push(node->right); } } } int main() { Student students[] = { {"Lei Zhenzi", 101401, 82}, {"Jiang Ziya", 100032, 90}, {"Ne Zha", 101674, 70}, {"Shen Gongbao", 101982, 87}, {"Jiu Weihu", 107431, 75}, {"Tian Zun", 100001, 98}, {"Tai Yi", 101009, 81}, {"Yang Jian", 101321, 63}, {"Huang Feihu", 101567, 72}, {"Zhou Wang", 108160, 55}, {"Li Jing", 102456, 84}, {"Tu Xingsun", 102245, 65}, }; int n = sizeof(students) / sizeof(Student); TreeNode* root = new TreeNode(students[0]); queue<TreeNode*> q; q.push(root); for (int i = 1; i < n; i += 2) { TreeNode* parent = q.front(); q.pop(); parent->left = new TreeNode(students[i]); q.push(parent->left); if (i + 1 < n) { parent->right = new TreeNode(students[i + 1]); q.push(parent->right); } } cout << "Post-order traversal: " << endl; postOrder(root); cout << "Pre-order traversal: " << endl; preOrder(root); cout << "Level-order traversal: " << endl; levelOrder(root); return 0; }
时间: 2023-06-27 17:06:55 浏览: 146
#include_iostream.h_
4星 · 用户满意度95%
这段代码实现了二叉树的三种遍历方式:后序遍历、前序遍历和层序遍历。它首先定义了两个结构体:`Student` 和 `TreeNode`。`Student` 是一个学生的结构体,包括姓名、学号和分数;`TreeNode` 是二叉树的结构体,包括数据和左右子树。
接下来,`postOrder` 函数用递归实现了后序遍历:先遍历左子树,再遍历右子树,最后输出根节点。`preOrder` 函数用栈实现了前序遍历:先将根节点入栈,然后每次取出栈顶元素,输出它的值,并将其右子树和左子树按顺序入栈。`levelOrder` 函数用队列实现了层序遍历:先将根节点入队列,然后每次取出队头元素,输出它的值,并将其左子树和右子树按顺序入队列。
在 `main` 函数中,首先定义了一个 `students` 数组,包括了所有学生的信息。然后创建了一个二叉树,根据数组中的数据构建出二叉树。最后分别调用 `postOrder`、`preOrder` 和 `levelOrder` 函数进行遍历输出。
阅读全文