数据结构二叉树中叶子结点的数目及二叉树的深度

来源:百度知道 编辑:UC知道 时间:2024/06/14 20:05:30
写一算法,求二叉树中叶子结点的数目. 试编制算法求出二叉树的深度,要求用C语言或者C++写出程序。

int BtreeDepth(BiTNode *BT){//求二叉树的深度
if (BT==NULL)//空树则返回0
return 0;
else{
int dep1=BtreeDepth(BT->lchild );//递归调用逐层分析
int dep2=BtreeDepth(BT->rchild );
if(dep1>dep2)
return dep1+1;
else
return dep2+1;
}
}
int Leave(BiTNode *BT){//求二叉树中的叶子节点数
if (BT==NULL)
return 0;
else{
if(BT->lchild ==NULL && BT->rchild ==NULL)
return 1;
else
return(Leave(BT->lchild )+Leave(BT->rchild ));
}
}

这是我学数据结构时做的练习,用的是递归的形式,理解时需稍稍的想一下,但是函数这样写起来会相对比较的简单。

希望对你的问题有所帮助,同时也祝你的问题早日得到解决,呵呵!

1.求叶结点数目
int cnt=0;

void CountLeaf(BTree T)
{
if(!T) return;
if(T->lc ==NULL && T->rc==NULL) cnt++;
CountLeaf(T->lc);
CountLeaf(T->rc);
}

2.求深度
int Depth(BTree T)
{
if(!T) return 0;
if(T->lc==NULL && T->rc==NULL) return 1;
int a,b;
a=De