Calculate the height of a binary tree.
The basic idea of using recursion to calculate the height of a tree is: for each non-empty node, first obtain the height of its left subtree, and then obtain the height of its right subtree, finally, take the height of one plus 1 in the two subtree as the height of the tree with this node as the root. For empty nodes, return 0 directly. To calculate the height of the entire tree, you only need to apply this idea to the root node.
Struct BST_Node {int m_value; BST_Node * left_child; BST_Node * rigth_child;}; class BSTree {private: int nodeCount; BST_Node * root ;... // The method for omitting the build object and other operations 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: BSTree (): nodeCount (0), root (NULL ){}... // The method int GetHeight () {return _ GetHeight (root) ;}// test code int _ tmain (int argc, _ TCHAR * argv []) {int myarray [] = {10, 6, 15, 4, 8, 1, 17, 14, 5, 13, 7, 11, 9, 12, 16}; BSTree tree ;... // The statement int height = tree for skipping the tree creation and first traversing the tree. getHeight (); cout
// Result