二叉树的操作
1.实验内容描述需求:
创建二叉树和实现二叉树的三种遍历
a. 根据提示输入字符型数据创建二叉树,输入值为所有字符型数据
b. 输出为遍历后的每个结点的值的顺序
c. 创建二叉树并能实现二叉树的先序、中序、后序遍历
d. 如果输入数据为:a b c
输出结果为:a b c
b a c
b c a
2.数据结构定义:
(1)二叉树,定义一个根,询问是否有左右孩子,有就添加,无则结束,依此下去
(2)本实验采用了链式存储结构,可以用以下程序来定义:
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
3.主程序的流程及各程序模块之间的调用关系
(1)二叉树的操作实验中,需要定义的函数有:
TreeNode* creatTree() 创建一个树,并把结果输入进去
void preorder(TreeNode* root) 先序输出
void inorder(TreeNode* root)中序输出
void postorder(TreeNode* root)后序输出
(2)
4.程序实现
#include <iostream>
using namespace std;
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* creatTree() {
char c;
cout << "please enter the data:";
cin >> c;
TreeNode* root = new TreeNode(c);
char choice;
cout << c <<" leftchild is null.add?y/n"<<endl;
cin >> choice;
if (choice == 'y') {
root->left = creatTree();
}
cout << c <<" rightchild is null.add?y/n"<<endl;
cin >> choice;
if (choice == 'y') {
root->right = creatTree();
}
return root;
}
void preorder(TreeNode* root) {
if (root == NULL) {
return;
}
cout << root->val << " ";
preorder(root->left);
preorder(root->right);
}
void inorder(TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
cout << root->val << " ";
}
int main() {
TreeNode* root = creatTree();
cout<<"程序退出,显示结果应为:" <<endl;
cout << "先序遍历: ";
preorder(root);
cout << endl;
cout << "中序遍历: ";
inorder(root);
cout << endl;
cout << "后序遍历: ";
postorder(root);
cout << endl;
return 0;
}
5.调试分析
(1)1.怎样才能结束程序:
用递归函数,当一个结点的左右孩子都没有时,结束此次输入,当根没有时,结束
2.怎样提示要输入什么:
用cout直接显示
3.先序后序中序的区别:
代码中输出的位置不同
(2)每个函数时间复杂度
TreeNode* creatTree() O(n)
void preorder(TreeNode* root) O(n)
void inorder(TreeNode* root) O(n)
void postorder(TreeNode* root)O(n)
6.运行结果:
7.总结:
本次实验方案选择合理,算法设计正确,运行结果达到预期