实验三
实验名称:二叉树的基本操作 | |
实验室名称:丹青909 | 实验台号:14 |
学生姓名: 陈佳龙 | 专业班级: 2015级1班 |
指导教师:于慧伶 | 实验日期:2017-6-9 |
一、实验目的
1、掌握二叉树的存储实现。
2、掌握二叉树的遍历思想。
3、掌握二叉树的常见算法的程序实现。
二、实验仪器及环境:
PC计算机;windows XP操作系统、Visual C++6.0、CodeBlocks
三、实验内容及结果(按照具体实验题目,按照如下格式书写)
1、
#include <iostream>
#include <cstdio>
#include <time.h>
#include <cstdlib>
#include <stack>
#include <queue>
using namespace std;
int LeafCount=0;
typedef struct Node{
char data;
struct Node *Lchild;
struct Node *Rchild;
}BitNode,*BiTree;
void CreateBiTree(BiTree *bt){
char ch;
ch=getchar();
// cin>>ch;
if(ch!='@'){
*bt=(BiTree)malloc(sizeof(BitNode));
(*bt)->data=ch;
CreateBiTree(&((*bt)->Lchild));
CreateBiTree(&((*bt)->Rchild));
}
else *bt=NULL;
}
void PreOrder(BiTree bt){//先序
if(bt==NULL) return;
cout<<bt->data<<" ";
PreOrder(bt->Lchild);
PreOrder(bt->Rchild);
}
void InOrder(BiTree bt){//中序
if(bt==NULL) return;
InOrder(bt->Lchild);
cout<<bt->data<<" ";
InOrder(bt->Rchild);
}
void PostOrder(BiTree bt){//后序
if(bt==NULL) return;
PostOrder(bt->Lchild);
PostOrder(bt->Rchild);
cout<<bt->data<<" ";
}
void inOrder2(BiTree root){//非递归中序遍历
stack<BiTree> s;
BiTree p=root;
while(p!=NULL||!s.empty())
{
while(p!=NULL)
{
s.push(p);
p=p->Lchild;
}
if(!s.empty())
{
p=s.top();
cout<<p->data<<" ";
s.pop();
p=p->Rchild;
}
}
}
int depth(BiTree root){
int ldepth,rdepth;
if(!root)
return 0;
else{
ldepth =depth(root->Lchild)+1;
rdepth =depth(root->Rchild)+1;
return max(ldepth,rdepth);
}
cout<<ldepth<<" "<<rdepth<<endl;
}
void Countleaf(BiTree root){
if(root!=NULL){
Countleaf(root->Lchild);
Countleaf(root->Rchild);
if(root->Lchild==NULL&&root->Rchild==NULL)
LeafCount++;
}
}
void PrintFromTopToBottom(BiTree T)
{
if(T == NULL)
return;
queue<BiTree> queueTreeNode;
queueTreeNode.push(T);
while(!queueTreeNode.empty())
{
BiTree pNode = queueTreeNode.front();
cout << pNode->data << " ";
queueTreeNode.pop();
if(pNode->Lchild != NULL)
queueTreeNode.push(pNode->Lchild);
if(pNode->Rchild != NULL)
queueTreeNode.push(pNode->Rchild);
}
}
void display(BiTree root) //显示树形结构
{
if(root!=NULL)
{
cout<<root->data;
if(root->Lchild!=NULL)
{
cout<<'(';
display(root->Lchild);
}
if(root->Rchild!=NULL)
{
cout<<',';
display(root->Rchild);
cout<<')';
}
}
}
int main()
{
BiTree bt;
int n;
cout<<"请按先序次序输入二叉树中结点的值,@表示空树:"<<endl;
CreateBiTree(&bt);
// cout<<"二叉树的树形显示:"<<endl;
// display(bt);
cout<<"先序递归遍历二叉树:"<<endl;
PreOrder(bt);cout<<endl;
cout<<"中序递归遍历二叉树:"<<endl;
InOrder(bt);cout<<endl;
cout<<"后序递归遍历二叉树:"<<endl;
PostOrder(bt);cout<<endl;
cout<<"中序非递归遍历二叉树:"<<endl;
inOrder2(bt);cout<<endl;
cout<<"二叉树的高度:";
n=depth(bt);
cout<<n<<endl;
cout<<"二叉树叶节点个数:";
LeafCount=0;
Countleaf(bt);
cout<<LeafCount<<endl;
cout<<"队列实现二叉树的层次遍历:"<<endl;
PrintFromTopToBottom(bt);
return 0;
}
7、
四、实验心得体会:(包括遇到的问题及解决办法)
创建二叉树时注意空节点,注意先序,中序和后序的递归遍历次序,非递归遍历和层次遍历时应用到之前学习的栈和队列知识。
五、指导教师意见及成绩
签名:
年 月 日