We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
You're not initialising the height at -1, the -1 happens at the end of the recursive loop. It is required, because when you hit a null node you have effectively gone beyond the bounds of what constitutes a valid tree.
It's hard to imagine an analogy, but let's say you were blindfolded and had to count a row of items placed in front of you. Maybe there are ten stones and a rubber duck, and you have to count the number of stones. You touch each item with your hand and count one.. two.. thre... until you count the duck. In your head you have reached 11, but because the duck is not a stone you have to subtract one to get back to 10.
Ok rubbish analogy, but the principle is the same here. My solution posted here is very similar to these algorithms, and it works for all the provided test cases, and in fact would work correctly on any input (within the constraints).
Think of it another way - If you return 0 for a null node then the code is definitely wrong, because a null tree does not have a height of 0. A tree of height 0 is a valid tree with one node - the root. That is different from a tree where the root node is null.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Height of a Binary Tree
You are viewing a single comment's thread. Return to all comments →
You're not initialising the height at
-1
, the-1
happens at the end of the recursive loop. It is required, because when you hit anull
node you have effectively gone beyond the bounds of what constitutes a valid tree.It's hard to imagine an analogy, but let's say you were blindfolded and had to count a row of items placed in front of you. Maybe there are ten stones and a rubber duck, and you have to count the number of stones. You touch each item with your hand and count one.. two.. thre... until you count the duck. In your head you have reached 11, but because the duck is not a stone you have to subtract one to get back to 10.
Ok rubbish analogy, but the principle is the same here. My solution posted here is very similar to these algorithms, and it works for all the provided test cases, and in fact would work correctly on any input (within the constraints).
Think of it another way - If you return
0
for anull
node then the code is definitely wrong, because anull
tree does not have a height of0
. A tree of height0
is a valid tree with one node - the root. That is different from a tree where the root node isnull
.