I\'m trying to know whether my code is right or wrong with your help, because sadly I can\'t run it to check.
There are no compile errors. What I\'m trying to do is to
Really compact version:
public int height(RBNode t) {
if (t == null) {
return 0;
}
return Math.max(height(t.left), height(t.right)) + 1;
}
At first glance, as long as you pass in the head of the tree, it'll return the correct value. But it should have been easy to construct a test to validate this...
Looks fine to me, although I'd personally change the last bit to:
return Math.max(heightLeft, heightRight) + 1;
I'm concerned that you can't run it at all though... why can you not write unit tests around this? I'd be nervous of any code I can't test :)
In the code in the question, are we not getting height +1? the height is defined as 'length of the path from the root to the deepest node in the tree. A (rooted) tree with only one node (the root) has a depth of zero.'(wikipedia)
if in question's code if give the root to a tree with just 1 node it will give height as 1, which should infact be 0..
Please correct me if i am wrong somewhere..