写在前面
1、基于2021级计算机类实验指导书
2、代码仅提供参考
3、如果代码不满足你的要求,请寻求其他的途径
运行环境
window11家庭版
CLion 2023.2.2
实验要求、源代码和运行结果
1、建立一棵二叉树,树的形态自定,完成以下操作:
(1)输出该二叉树的前序遍历序列;
(2)输出该二叉树的中序遍历序列;
(3)输出该二叉树的后序遍历序列。
建立的二叉树结构如下(示例,数据可以修改)
1
/ \
2 3
/ \ / \
4 5 6 7
#include <iostream>
#include <vector>
using namespace std;
// 二叉树节点结构定义
struct Node {
int value;
Node* left;
Node* right;
Node(int val) : value(val), left(nullptr), right(nullptr) {}
};
// 前序遍历
void preorderTraversal(Node* root, vector<int>& result) {
if (root == nullptr) {
return;
}
result.push_back(root->value);
preorderTraversal(root->left, result);
preorderTraversal(root->right, result);
}
// 中序遍历
void inorderTraversal(Node* root, vector<int>& result) {
if (root == nullptr) {
return;
}
inorderTraversal(root->left, result);
result.push_back(root->value);
inorderTraversal(root->right, result);
}
// 后序遍历
void postorderTraversal(Node* root, vector<int>& result) {
if (root == nullptr) {
return;
}
postorderTraversal(root->left, result);
postorderTraversal(root->right, result);
result.push_back(root->value);
}
// 根据用户输入构建二叉树
Node* buildBinaryTree() {
int value;
cout << "请输入节点的值(输入-1表示节点为空):" << endl;
cin >> value;
if (value == -1) {
return nullptr;
}
Node* root = new Node(value);
cout << "构建节点 " << value << " 的左子树:" << endl;
root->left = buildBinaryTree();
cout << "构建节点 " << value << " 的右子树:" << endl;
root->right = buildBinaryTree();
return root;
}
int main() {
cout << "构建二叉树:" << endl;
Node* root = buildBinaryTree();
// 前序遍历
cout << "前序遍历序列:"<<endl;
vector<int> preorderResult;
preorderTraversal(root, preorderResult);
for (int val : preorderResult) {
cout << val << " ";
}
cout << endl;
// 中序遍历
cout << "中序遍历序列:"<<endl;
vector<int> inorderResult;
inorderTraversal(root, inorderResult);
for (int val : inorderResult) {
cout << val << " ";
}
cout << endl;
// 后序遍历
cout << "后序遍历序列:"<<endl;
vector<int> postorderResult;
postorderTraversal(root, postorderResult);
for (int val : postorderResult) {
cout << val << " ";
}
cout << endl;
return 0;
}