二叉树的节点个数等于左子树的节点数加上右子树的节点数再加上根节点数1。
递归算法:
template<class ElemType>
int BinaryTree<ElemType>::NodeCountHelp(const BinTreeNode<ElemType>* r)const
//操作结果:返回以r为根的二叉树的节点个数
{
//空二叉树节点个数为0
if (r == NULL) return 0;
//非空二叉树节点个数为左右子树的节点个数加一
else return NodeCountHelp(r->leftChild) + NodeCountHelp(r->rightChild) + 1;
}
二叉树高的定义:空树高为0,非空树高为其左右子树高的最大值加1
算法代码:
template<class ElemType>
int BinaryTree<ElemType>::HeightHelp(const BinTreeNode<ElemType>* r)const
//操作结果:返回以r为根的二叉树的高
{
if (r == NULL)
{
//空二叉树高为0
return 0;
}
else
{
//非空二叉树高为左右子树的高的最大值再加一
//左子树的高
int lHeight = HeightHelp(r->leftChild);
//右子树的高
int rHeight = HeightHelp(r->rightChild);
//高为左右子树的高的最大值再加一
return (lHeight> rHeight? lHeight: rHeight)+1;
}
}