-2

i tried this function

private int height(AVLNode t )
{
    return t == null ? -1 : t.height;
}

i don't know what that method do can anyone explain it ?

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
user3766910
  • 45
  • 1
  • 8

4 Answers4

4

The default approach is to use recursion to determine the height.

private int height(AVLNode t) {
    return t == null ? -1 : 1 + Math.max(height(t.left), height(t.right));
}
muued
  • 1,666
  • 13
  • 25
  • Although for larger problems, you can imagine how this becomes slower. That's why during initialization of this node, it might be better to save the height as an instance variable using its parent's height. But for the problem OP is talking about, this is probably the way to go. – NoseKnowsAll Apr 30 '15 at 15:11
  • I was puzzled concerning the use of the function, since its private and takes a Node as parameter. If the nodes know their height, why add the non-null check except for empty trees, but then again why is there a parameter, if its supposedly only used with t == root. So I figured I'd suggest the recursive way. – muued Apr 30 '15 at 15:17
1

It returns the height of the AVLNode. If the AVLNode is null it returns -1. If the AVLNode is not null it returns the height of the AVLNode.

bcam909
  • 168
  • 11
1

The method returns height of the AVLNode, -1 otherwise. The line return t == null ? -1 : t.height is a ternary operator

Is equivalent to

if (t == null) {
    return -1
} else {
    return t.height
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0
private int height(AVLNode t) {

        if (t == null) {
            return 0;
        }

        return 1 + Math.max((t.getLeft() != null ? t.getLeft().getHeight() : -1),
                (t.getRight() != null ? t.getRight().getHeight() : -1));

}
Rajitha Udayanga
  • 1,559
  • 11
  • 21