二叉树求解树高度类
以此树为例:
一、求二叉树的最大深度
int getMaxDepth(BiTree* T) {
if (T == NULL)
{
return 0;
}
//递归求左子树的高度
int ldep = getMaxDepth(T->lchild) ;
//递归求右子树的高度
int rdep = getMaxDepth(T->rchild) ;
//返回最大深度
return max(ldep, rdep) + 1;
}
二、求二叉树的最小深度
分析:
(1)如果二叉树为空,则返回0;
(2)如果二叉树不为空,则递归计算根结点的左孩子、右孩子的深度,取出最小值,然后+1就是该二叉树的最小深度;
(3)如果二叉树没有右(左)孩子,则二叉树最小深度 = 左(右)孩子深度+1;
int getMinDepth(BiTree* T) {
if (T == NULL)
{
return 0;
}
if (T->lchild == NULL && T->rchild == NULL)
{
return 1;
}
//递归求左右子树的高度
int ldep = getMinDepth(T->lchild);
int rdep = getMinDepth(T->rchild);
//如果二叉树没有右(左)孩子,置右(左)子树深度为无穷大
if (ldep == 0)
{
ldep = INT_MAX;
}
if (rdep == 0)
{
rdep = INT_MAX;
}
//返回最小深度
return min(ldep, rdep) + 1;
}
三、结果展示
cout << "树的最大高度为:" << getMaxDepth(T) << endl;
cout << "树的最小高度为:" << getMinDepth(T) << endl;