二叉树算法设计
【可操作的菜单项目】
(1) 创建二叉树;
(2) 显示二叉树
(3) 求树高
(4) 统计叶子结点
【基本要求】
(1)建立含有若干个元素的二叉链表,要求从文件读入数据,显示函数公用。
(2)计算并显示二叉树的高度。
(3)计算并显示二叉树叶子结点数。
执行程序:
代码:
#include<iostream>
using namespace std;
#include"c.cpp"
void main()
{
char zxz;
int c=0;
while(!c)
{
cout<<"☆☆☆☆☆☆☆☆☆☆☆☆☆二叉树算法设计☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆"<<endl;
cout<<"★ A 创建二叉树 ★"<<endl;
cout<<"☆ B 显示二叉树 ☆"<<endl;
cout<<"★ C 求树高 ★"<<endl;
cout<<"☆ D 统计叶子节点 ☆"<<endl;
cout<<"★ E 结束 ★"<<endl;
cout<<"☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆"<<endl;
cout<<" 请输入A~E进行选择: ";
cin>>zxz;
BiTree T;
switch(zxz)
{
case 'A' :
{
cout<<"请按先序次序输入各结点的值,以#表示空树(输入时可连续输入): "<<endl;
cout<<"创建二叉树:"<<endl;
CreateBiTree( T);
break;
}
case 'B' :
{
cout<<"显示二叉树 "<<endl;
PrintBiTree(T);
cout<<endl;
break;
}
case 'C' :
cout<<"求树高 "<<Height(T)<<endl;
break;
case 'D' :
cout<<"统计叶子节点 "<<countleaf(T)<<endl;
cout<<endl;
break;
case 'E' : cout<<" 结束!!!"<<endl; c=1; break;
default:
cout<<" 出错,重新选择!"<<endl;
}
}
}
#include <stdio.h>
#include <iostream>
#include <queue>
#include <stack>
#include <malloc.h>
#define SIZE 100
using namespace std;
typedef struct BiTNode //定义二叉树节点结构
{
char data; //数据域
struct BiTNode *lchild,*rchild; //左右孩子指针域
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T); //生成一个二叉树
void PrintBiTree ( BiTree &T);//显示二叉树
void CreateBiTree(BiTree &T)
{
char ch;
cin>>ch; //读入一个字符
if(ch=='#') T= NULL;
else
{
T=(BiTNode *)malloc(sizeof(BiTNode)); //生成一个新结点
T->data=ch;
CreateBiTree(T->lchild); //生成左子树
CreateBiTree(T->rchild); //生成右子树
}
}
//显示二叉树
void PrintBiTree ( BiTree &T) { //输出二叉树的算法
if ( T != NULL ) { //树为空时结束递归
cout << T -> data ; // 输出根结点的值
if (T -> lchild != NULL || T -> rchild != NULL ) {
cout <<'(' ; // 输出左括号
PrintBiTree (T -> lchild); // 输出左子树
cout <<',' ; // 输出逗号分隔符
if ( T -> rchild != NULL )
PrintBiTree (T -> rchild); // 输出右子树
cout <<')' ; } // 输出右括号
}
}
//求树高
int Height(BiTree &T)
{
int h1;
int h2;
if(!T)
{
return 0;
}
else
{
h1=Height(T->lchild);
h2=Height(T->rchild);
if(h1>=h2)return 1+h1;
else return 1+h2;
}
}
//求叶子的结点
int countleaf(BiTree &T)
{
if(!T)
return 0; //空树,无叶子
else if(!T->lchild && !T->rchild)
return 1;
else
return (countleaf(T->lchild) + countleaf(T->rchild));
}