Calculate the height of a binary tree.

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.