二叉树的创建及基本操作
内容:
1.利用二叉树的二叉链表存储方法按照先序遍历序列创建二叉树,实现三种递归遍历算法。
2.编写统计二叉树的叶子结点及求二叉树深度的算法(可用递归方法)。
3.实现二叉树的非递归中序遍历算法。
二叉链表存储表示:
typedef struct BiTNode{
TElemType data;
struct BiTNode *lchild, *rchild;
} BiTNode,*BiTree;
算法设计及程序源代码
- 二叉树的创建算法(按先序遍历序列创建):
BiTree creatbitree(){
BiTree T;
TElemType ch;
scanf("%c",&ch);
if(ch=='#') T=NULL;//#代表空格字符
else{
T=(BiTNode*)malloc(sizeof(BiTNode));
T->data=ch;//生成根结点
T->lchild=creatbitree();//生成左子树
T->rchild=creatbitree();//生成右子树
}
return T; }
2.统计二叉树叶子结点个数的算法:
int countleaf(BiTree T,int count) {
if(T){
if((T->lchild==NULL)&&(T->rchild==NULL))
count++;
count=countleaf(T->lchild,count);
count=countleaf(T->rchild,count);}
return count;}
3.求二叉树深度的算法:
int bitreedepth(BiTree T) {
int leftdepth,rightdepth,maxdepth;
if(T!=NULL){
leftdepth=bitreedepth(T->lchild) ;//左子树深度
rightdepth=bitreedepth(T->rchild) ;//右子树深度
maxdepth=leftdepth>rightdepth?leftdepth:rightdepth;//取最大深度
return maxdepth+1;}
else return 0; }
4.先序、中序、后序递归遍历算法:
先序:
void preorder(BiTree T) {
if(T!=NULL){
printf("%c ",T->data);
preorder