大致思路
首先定义了计算树高的迭代函数getHeightRec(),它的参数是当前节点,函数从根节点进入,判断不是叶子节点后计算其左子树和右子树的树高,并返回其中高的那一个并加一(当前节点的一个树高),如此迭代,直到迭代到叶子节点后按顺序返回,最后输出树高。
部分代码
//计算树高的迭代函数
template<typename T>
int BinSearchTree<T>::getHeightRec(Node* tempRoot) const {
if (tempRoot == NULL) return -1; //空树的树高定义为-1
int leftHeight = getHeightRec(tempRoot->left); //计算并返回左子树树高
int rightHeight = getHeightRec(tempRoot->right); //计算并返回右子树树高
//以左右子树高的为准,加上自己这个节点,返回当前树高
if (leftHeight > rightHeight) return leftHeight+1;
else return rightHeight+1;
}
template<typename T>
int BinSearchTree<T>::height() const
{
return getHeightRec(root); //计算树高迭代函数
}
实验总结
在计算树高时,把问题递归化成,二叉树的树高等于左右子树较高的树高加一。