求二叉树的深度
算法思想:用的是递归的思想,从根结点开始往左子树遍历,遍历完左子树再往右子树遍历,遍历到低端,无法向下遍历,此时返回一个0,返回上层栈。最后得到二叉数的深度。
# include <stdio.h>
# include <stdlib.h>
typedef struct BiNode
{
BiNode *leftchild;
int data;
BiNode *rightchild;
}BiNode,*BiTree;
//建立二叉树
void BuildBiTree(BiTree&T)
{
T=(BiTree)malloc(sizeof(BiNode));
char ch;
scanf("%c",&ch);
if(ch=='#')
T==NULL;
else
{
T->data=ch;
BuildBiTree(T->leftchild);
BuildBiTree(T->rightchild);
}
}
如果对于上面的代码有疑问的话,可以去看我的另外一篇博客,希望能帮助到大家。编者是大学生,有不对的地方,还请大家一定要指出!!!谢谢^ _ ^
求二叉树的深度
int DepthBiTree(BiTree &T)
{
int r,l; //表示左右子树
if(T==NULL) //没有结点
return 0;
else if(T->leftchild==NULL && T->rightchild==NULL)//没有左右子树
return 1;
else
{
l=DepthBiTree(T->leftchild); //递归左子树
r=DepthBiTree(T->rightchild); //递归右子树
if(r>=l)
return r+1;
else
return l+1;
}
}
求叶结点的个数
这个其实和求深度是差不多的,都是用递归遍历实现,到最底层都是0或者1个结点
int GetLeaf(BiTree &T)
{
if(T==NULL)
return 0;
else if(T->leftchild==NULL&&T->rightchild==NULL)
return 1;
else
return
(GetLeaf(T->leftchild)+GetLeaf(T>rightchild));
}
接下来主函数
int main()
{
BiTree T;
int d;
int n;
printf("请输入数据,'#'不建立子树 ");
BuildBiTree(T);
d=DepthTree(T);
printf("二叉树的深度为:%d\n",d);
n=GetLeaf(T);
printf("二叉树的叶结点的个数为:%d\n",n);
system("system");
return 0;
}
附上运行截图,有不对的还请大家指正,谢谢!!!