前端之家收集整理的这篇文章主要介绍了
《数据结构》实验五: 树和二叉树实验,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
《数据结构》实验五: 树和二叉树实验
一..实验目的 巩固树和二叉树的相关知识,特别是二叉树的相关内容。学会运用灵活应用。1.回树和二叉树的逻辑结构和存储方法,清楚掌握树和二叉树的遍历操作。2.学习树的相关知识来解决实际问题。3.进一步巩固程序调试方法。4.进一步巩固模板程序设计。二.实验时间 准备时间为第10周到第12前半周,具体集中实验时间为12周周四。2个学时。三..实验内容
1.自己设计一个二叉树,深度最少为4,请递归算法分别用前序、中序、后序遍历输出树结点。
前序遍历源代码:
- #ifndef Tree_H
- #define Tree_H
- struct BiNode
- {
- char data;
- BiNode *lchild,*rchild;
- };
-
-
- class Tree
- {
- public:
- Tree(){root=Creat(root);}
- ~Tree(){Release(root);}
- void PreOrder(){PreOrder(root);}
- private:
- BiNode*root;
- BiNode*Creat(BiNode*bt);
- void Release(BiNode*bt);
- void PreOrder(BiNode*bt);
- };
- #endif
-
- #include<iostream>
- using namespace std;
- #include "二叉链表.h"
- BiNode *Tree::Creat(BiNode *bt)
- {
- char ch;
- cout<<"请输入创建一棵二叉树的结点数据:"<<endl;
- cin>>ch;
- if(ch=='#')return NULL;
- else
- {
- bt=new BiNode;
- bt->data=ch;
- bt->lchild=Creat(bt->lchild);
- bt->rchild=Creat(bt->rchild);
- }
- return bt;
- }
-
-
- void Tree::Release(BiNode *bt)
- {
- if(bt!=NULL)
- {
- Release(bt->lchild);
- Release(bt->rchild);
- delete bt;
- }
- }
-
-
- void Tree::PreOrder(BiNode *bt)
- {
- if(bt==NULL)return;
- else
- {
- cout<<bt->data<<" ";
- PreOrder(bt->lchild);
- PreOrder(bt->rchild);
- }
- }
-
- #include<iostream>
- using namespace std;
- #include "二叉链表.h"
- int main()
- {
- Tree T;
- cout<<"------前序遍历------"<<endl;
- T.PreOrder();
- cout<<endl;
- return 0;
- }