利用递归来求一棵树的高度,基本思想是:对于每一个非空节点,先求取其左子树的高度,然后求取其右子树的高度,最后取两子树中较高的一个加1作为以该节点为根的树的高度;对于空节点,直接返回0就可以了。求整棵树的高度只需将此思想运用到根节点上即可。
struct BST_Node
{
int m_value;
BST_Node* left_child;
BST_Node* rigth_child;
};
class BSTree
{
private:
int nodeCount;
BST_Node* root;
...//省略建树及其他操作的方法
int _GetHeight(BST_Node* node)
{
if(node == NULL)
return 0;
int leftHeight = _GetHeight(node->left_child);
int rightHeight = _GetHeight(node->rigth_child);
int GreaterHeight = leftHeight > rightHeight ? leftHeight : rightHeight;
return 1 + GreaterHeight;
}
public: