一、实验内容
1、自己确定一个二叉树(树结点类型、数目和结构自定)利用链式存储结构方法存储。实现树的构造,并完成:
1)用前序遍历、中序遍历、后序遍历输出结点数据;
2)以合理的格式,输出各个结点和双亲、孩子结点信息;
3)输出所有的叶子结点信息;
二、源代码
#include<iostream>
#include<string>
const int MAXSIZE = 100;
using namespace std;
struct Node {
Node*lchild;
Node*rchild;
string data;
};
class Tree {
private:
Node*root;
void release(Node*bt);
Node*Create(Node*bt);
void preorder(Node*bt);
void inorder(Node*bt);
void postorder(Node*bt);
void print(Node*bt);//输出叶子结点
void printlist(Node*bt);//输出
public:
void preorder(){preorder(root);}//前序遍历
void inorder() { inorder(root); }//中序遍历
void postorder() { postorder(root); }//后序遍历
void leverorder();//层序遍历
Tree() { root = Create(root); }
~Tree() { release(root); }
void print() { print(root); }
void printlist() { printlist(root); }
};
Node*Tree::Create(Node*bt) {
string ch;
cout << "输入数据ch:";
cin >> ch;
if (ch == "NULL") { bt = NULL; }
else {
bt = new Node;
bt->data = ch;
cout << "输入左孩子:";
bt->lchild = Create(bt->lchild);
cout << "输入右孩子:";
bt->rchild = Create(bt->rchild);
}
return bt;
}
void Tree::release(Node*bt) {
if (bt != NULL) {
release(bt->lchild);
release(bt->rchild);
delete bt;
}
}
void Tree::preorder(Node*bt) {
if (bt == NULL) {
return;
}
else {
cout << bt->data << "\t";
preorder(bt->lchild);
preorder(bt->rchild);
}
}
void Tree::inorder(Node*bt) {
if (bt == NULL) {
return;
}
else {
inorder(bt->lchild);
cout << bt->data << "\t";
inorder(bt->rchild);
}
}
void Tree::postorder(Node*bt) {
if (bt == NULL) {
return;
}
else {
postorder(bt->lchild);
postorder(bt->rchild);
cout << bt->data << "\t";
}
}
void Tree::leverorder() {
int front = -1; int rear = -1; Node*Q[MAXSIZE];
if (root == NULL) { cout << "NULL"; }
else {
Q[++rear] = root;
while (front != rear) {
Node*q = new Node;
q = Q[++front];
cout << q->data << "\t";
if (q->lchild != NULL) { Q[++rear] = q->lchild; }
if (q->rchild != NULL) { Q[++rear] = q->rchild; }
}
}
}
void Tree::print(Node*bt) {
if(bt!=NULL){
if (!bt->lchild && !bt->rchild)
cout << bt->data << '\t';
print(bt->lchild);
print(bt->rchild);
}
}
void Tree::printlist(Node*bt) {
if (bt == NULL)return;
else{
if (bt != NULL&&bt->data != "NULL")
cout << "结点数据为:" << bt->data << endl;
if (bt->lchild != NULL)
cout << "左孩纸:" << bt->lchild->data << endl;
if (bt->rchild != NULL)
cout << "右孩纸:" << bt->rchild->data << endl;
cout << "\n";
}
printlist(bt->lchild);
printlist(bt->rchild);
}
int main() {
Tree T;
cout << "\n";
cout << "前序遍历:";
T.preorder();
cout << "\n";
cout << "中序遍历:";
T.inorder();
cout << "\n";
cout << "后序遍历:";
T.postorder();
cout << "\n";
cout << "层序遍历:";
T.leverorder();
cout << "\n";
cout << "输出所有结点的关系:" << endl;
T.printlist();
cout << "\n";
cout << "输出所有叶子结点:";
T.print();
cout << "\n";
cout << "下期美食介绍敬请期待~~";
}
三、实验结果
四、总结与反思
1、二叉链表实验出于安全性考虑,把函数的实际算法放在private中,当对象要调用函数时要通过public函数调用。
2、层序遍历是使用队列进行操作。这是比较难懂的一个点