1.二叉树求深度(一般求法)
在递归计算深度时,我们应该将当前节点的左右子树分别递归求解深度,然后取其中较大的值加1即为当前节点所在二叉树的深度。
int GetDepthOfBiTree ( BiTree T)
{
if (!T) return 0; // 如果节点为空,则深度为0
int ldepth = GetDepthOfBiTree(T->lchild);// 左子树深度
int rdepth = GetDepthOfBiTree(T->rchild);// 右子树深度
return (ldepth > rdepth ? ldepth : rdepth) + 1;// 当前节点为根的二叉树深度为较大值加1
}
2.二叉树求叶子结点个数
int LeafCount(BiTree T)
{
int c;
if (!T) c = 0;//结点为空,叶子结点为0
else if (!T->lchild && !T->rchild) c = 1;//左右孩子同时为空,则该节点为叶子节点,个数为1;
else c = LeafCount(T->lchild) + LeafCount(T->rchild);//递归左右数的叶子节点数
return c;
}
3. 求二叉树的分枝结点(非终端结点)个数
//函数原型
int BinTreeNumBranch(const TNODE *root);
//实现代码如下:
int BinTreeNumBranch(const TNODE *root)
{
if (root == NULL) return 0;
else return ((root->lch || root->rch) & 1) + BinTreeNumBranch(root->lch) + BinTreeNumBranch(root->rch);
}