Why is this code not working for Hackerrank Day 22

Why is this code not working for Hackerrank Day 22

hi @cbcao263 the correct way to calculate the height of a binary tree is to take the max of the height of left subtree and right subtree, and then add 1 to it for the current level. Right now you are adding both the heights of left and right subtrees, but if you do a dry run, you will see that that is wrong.
The correct statement should be
return 1+ max(getHeight(root->left), getHeight(root->right));
Calculating height has been covered in the course as well, you can check out the video. If you still have any confusion you can refer to this article

Please mark the doubt as resolved if you do not have any further queries.


Mam This is even showing error. Please tell for that.

@cbcao263 you didnt add the base case here.
This will be the correct function

int getHeight(Node* root){
            if (!root) {
                return 0;
            }
            return 1 + max(getHeight(root->left), getHeight(root->right));
}

I should add that the question given on hackerrank is not considering this as the correct answer, It is considering the “height” of tree to be 1 less than it actually is. You can see that from the article link I provided. So I guess you can print the answer by subtracting 1 from it to fit this question, but also remember what height actually is :slight_smile:

Mam Even this code is not working,


And One More help needed, It is very difficult to me to implement the codes like I am currently on Graphs Section so I find it very difficult to implement and at last I used to cram that.
What should be solution for that?

@cbcao263 i already told you, this problem isnt asking for actual height, if you want to practice the “height” question specifically, you can do the leetcode one that is perfectly fine. As for graphs, it is a difficult topic indeed so you just be patient and try to clear all your doubts before you move on from any problem. Dont cram, try to understand.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.