0

For my AVL Tree implementation, I have a node which has a left, right and parent pointer, and a balance variable. Each time I am inserting a new node and carrying out the required rotation, I am updating the balance by subtracting the right sub-tree from the left sub-tree. This method in question calls itself recursively to calculate the height.

The method in question:

private int getHeight(Node nd){
    if (nd != null){
        if (nd.getLeft() == null && nd.getRight() == null)
            return 0;
        else if (nd.getLeft() == null)
            return getHeight(nd.getRight()) + 1;
        else if (nd.getRight() == null)
            return getHeight(nd.getLeft()) + 1;
        else
            return Math.max(getHeight(nd.getLeft()), getHeight(nd.getRight())) + 1;
    }
    else return -1;
}

My question is, since an AVL Tree Insert time complexity is O(log n), I think this method affects on this time complexity. What can be done to amend it?

chris05
  • 735
  • 4
  • 13
  • 27

3 Answers3

1

Hint: You don't need the heights to calculate the new balance. The old balance values of the node and its left and right children is enough.

Henry
  • 42,982
  • 7
  • 68
  • 84
1

You don't need the height. You can keep it balanced knowing the old balances. That said, you will probably need to adjust your rotations if you haven't already written it so that you keep your balance updated on every "move".

SBI
  • 2,322
  • 1
  • 17
  • 17
1

you don't need to calculate the Balance factor for all node in each insertion .

you just need to calculate for the parent of your inserted node , and also their parents , while you reach a node with Balance 2 or -2 and then rotate them.

if you don't know how to rotate theme in this way ( which rotate is suitable ) please inform me

Erfan Tavakoli
  • 336
  • 1
  • 6
  • 14