求二叉树叶子结点数和高度
成 绩 实验七
实验
目:求二叉树叶子结点数和高度 一、实验目的
• 加深理解二叉树的定义和特性;
• 掌握二叉树的存储结构与实现;
• 掌握二叉树的遍历操作及其应用
二、实验内容:
根据键盘输入的扩展二叉树的前序遍历序列建立相应的二叉树,并计算该二叉树的叶子结
点个数和高度。
三、
与编码
1、基本思想
利用二叉树的前序遍历操作,叶子结点个数和二叉树深度,设计递归算法实现。
2、编码
#include
using namespace std; struct BiNode
{
char data;
BiNode *lchild, *rchild;
};
class BiTree
{
public:
BiTree()
{
root=Creat(root);
}
~BiTree()
{
Release(root);
}
BiNode * Getroot()
{
return root;
}
void PreOrder(BiNode *root)
{
if(root==NULL)
return;
else
{
cout<data<<' ';
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
int LeafCount(BiNode *root)
{
if(root==NULL)
return 0;
else
{
if(root->lchild==NULL&&root->rchild==NULL)
return 1;
else
return LeafCount(root->lchild)+LeafCount(root->rchild);
}
}
int Height(BiNode *root)
{
int hl,hr,h;
if(root==NULL)
return 0;
else
{
hl=Height(root->lchild);
hr=Height(root->rchild);
h=(hl>hr?hl:hr)+1;
}
return h;
}
private:
BiNode *root;
BiNode *Creat(BiNode *bt)
{
char ch;
cin>>ch;
if(ch=='#')return 0;
else
{
bt=new BiNode;bt->data=ch;
bt->lchild=Creat(bt->lchild);
bt->rchild=Creat(bt->rchild);
}
return bt;
}
void Release(BiNode *bt)
{
if(bt==NULL)
{
Release(bt->lchild);
Release(bt->rchild);
delete bt;
}
}
};
int main()
{
cout<<"请输入创建一棵二叉树的结点数据:"<报告上交电子版,由学委统一发到我邮箱:yulwf@163.com,上交时间为下次实验课之前。实验报告一定要按时交,不能抄袭~~否则,后果自负。
每次实验一个文件夹,文件夹名称为学号+姓名;内包含两个文件:1,实验报告 2,源程序