简体   繁体   中英

Find the height of a tree

Can you make me understand this code to find the height of a binary tree:

   int lDepth = maxDepth(node->left);
   int rDepth = maxDepth(node->right);

   /* use the larger one */
   if (lDepth > rDepth) 
       return(lDepth+1);
   else return(rDepth+1);

I am not able to understand how " int lDepth = maxDepth(node->left); " will return the height of left subtree as when it reaches the base case...it will return 0. (code is incomplete).

i am not able to understand how "int lDepth = maxDepth(node->left);" will return the height of left subtree as when it reaches the base case...it will return 0. (code is incomplete).

True it will return 0, but don't forget the +1, imagine it reaches a case where the tree has a left and right node (no grandchild), the height of the left is 0 and of the right is 0 so depth of the parent is the depth of largest +1 which is 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM