目录
1、程序需求分析:
(1)输入的形式和输出值的范围;
输入的形式:例如输入abdh##i##ej##k##cfl###g##,当为#符号是则子树为NULL;输出值的范围:定义的数据域为char类型(2)输出的形式;将数据域中的数据先序遍历输出(3)程序所能达到的功能;输出先序遍历的结果;输出二叉树总结点数;输出二叉树叶子结点的个数;
2、主程序的流程及各程序模块之间的调用关系:
CreateTree(Tree1 &T):创建二叉链表的函数;
Leafnode(Tree1 &T):计算叶子结点的函数;
Treenode(Tree1 &T):计算总结点个数的函数;
ergodic(Tree1 &T):先序遍历;
ergodic2(Tree1 &T):中序遍历;
Ergodic3(Tree1 &T):后序遍历;
destroy(Tree1 &T):销毁二叉树释放空间的函数;
3、数据结构相关定义:
非线性结构链式存储
以下程序来定义:
typedef struct Student{
char data;
struct Student *lchild;
struct Student *rchild;
}Tree,*Tree1;
4、源码分析:
各个函数用到的递归函数知识比较多 读者也可以采用其他非递归实现各个函数的功能噢!
//(1) 编程实现创建二叉链表;
typedef struct Student{
char data;
struct Student *lchild;
struct Student *rchild;
}Tree,*Tree1;
//按先序遍历的顺序建立二叉链表
void CreateTree(Tree1 &T){
char ch;
cin>>ch;
if(ch == '#') T=NULL;
else {
T=new Tree;
T->data=ch;
CreateTree(T->lchild);
CreateTree(T->rchild);
}
}
//计算叶子节点的个数
int Leafnode(Tree1 &T){
if(T==NULL) return 0;
if(!T->lchild&&!T->rchild) return 1;
int s=Leafnode(T->lchild);
int d=Leafnode(T->rchild);
return (s+d);
}
//计算二叉树的节点的个数
int Treenode(Tree1 &T){
if(!T) return 0;
else return Treenode(T->lchild) + Treenode(T->rchild)+1;
}
//二叉树的遍历//先序遍历
void ergodic(Tree1 &T){
if(!T) return ;
cout<<T->data<<endl;
ergodic(T->lchild);
ergodic(T->rchild);
}
//中序遍历
void ergodic2(Tree1 &T){
if(!T) return ;
ergodic2(T->lchild);
cout<<T->data<<endl;
ergodic2(T->rchild);
}
//后序遍历
void ergodic3(Tree1 &T){
if(!T) return ;
ergodic3(T->lchild);
ergodic(T->rchild);
cout<<T->data<<endl;
}
//销毁二叉树
void destroy(Tree1 &T){
if(!T) return ;
destroy(T->lchild);
destroy(T->rchild);
delete T;
T=NULL;
}
5、函数之间的调用演示:
int main(){
Tree1 p;
cout<<"开始输入数据吧(例如abdh##i##ej##k##cfl###g##)创建二叉链表:"<<endl;
CreateTree(p);
cout<<"二叉树创建成功"<<endl;
cout<<"先序遍历为:"<<endl;
ergodic(p);
cout<<"二叉树的总节点数为:"<<endl;
int z = Treenode(p);
cout<<z<<endl;
cout<<"二叉树的叶子节点为:"<<endl;
int z1 = Leafnode(p);
cout<<z1<<endl;
cout<<"任意点一下就销毁二叉树了"<<endl;
system("pause");
destroy(p);
return 0;
}
//实验数据
//输入 abdh##i##ej##k##cfl###g##
//先序遍历
//abdhiejkcflg
6、程序结果演示: