Welcome to the Ranch
I thought it was supposed to be called, “depth.” Also I think that the parameter
root is poorly named because you won't always call that method on the root node.
Who gave you that code? Did they tell you it is incorrect?
That looks like a recursive function. What you are doing is finding the depth of your
root Node. So you look at the left, and that has a depth, and you look on the right, and that has a depth. Now, you work out which is larger, which you can either do with the expression
(i > j ? i : j) or
Math.max(i, j), which actually does the same. Then you add one because you have gone one level down into the tree.
Then you do the same for the left branch and the right branch, and all works well until you get to a node which isn't a branching node with both left and right branches. Then one or other branch's absence is represented by a
null. It won't take you long to find a
null, because a binary tree contains one more
null than it contains nodes. At which point it becomes impossible to call the
height() method and you have an
Exception thrown.
* * * * * * * * * * * * * * * * *
In order to get recursion to work, you need a “base case.” That is where the recursion stops and some default value is returned from the method. If you don't stop the recursion, it will keep going until something goes wrong, e.g., you exhaust stack memory or some other essential resource. 0 is a common base case return value.
You need to allow for the possibility of
nulls. I shall use the
?: operator for that.
I gave that method
private access assuming that Node is a nested class inside BinaryTree. The enclosing class has access to
private members of its nested classes.
Since every path through a binary tree eventually leads to a
null, you will eventually hit your base case, where the depth comes to 0.
Since every node has
left and
right fields, you don't need to pass arguments to that method.
Since the depth of an empty tree, a tree whose
root node is
null is 0, you will have to arrange to call that method such that it gives 0 for a completely empty tree, which is quite easy if the two classes are nested.