Question

I know there are many functions to be found out there where you can easily get the height of the Binary search tree by recursively calling the function and using the root of the node as the parameter every time for the left and right subtree. But what am I supposed to do when I won't be taking parameters on a Treap but it still return an int. I have been able to call other methods recursively but I am stopped on this one. Some help would be greatly appreciated!

This is what I have but I largely believe it's wrong

public int height()
{
    if(temp == null)
        return 0;
    else
    {
        temp = temp.left;
        temp = temp.right;
        return Math.max(height(), height()) + 1;
    }
}

No correct solution

OTHER TIPS

Since you are writing Java, it is not necessary to pass parameters explicitly: you get one parameter "for free" - namely, the target object of the method call.

For that to work, the height() method needs to be defined on the tree node object. Now the method definition is simple: in order for your Node object to know its height(), it needs to return either

  • the larger of the heights of your left and and your right subtrees, plus one for the node itself, or
  • one if both the left and the right subtrees are null.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top