Zia ur Rahman
Zia ur Rahman

Reputation: 1431

Calculating the balance factor of a node in avl tree

I want to calculate the balance factor of a node in avl tree without using any recursive procedure. How can i do that? Please tell me method or provide C++ code snippet.

Upvotes: 0

Views: 7484

Answers (2)

Gaim
Gaim

Reputation: 6844

Without recursion it can be a little complicated but you can save node height in each node. Then you can get balanced factor in constant time ( difference between left and right child height, if child is NULL then height is 0 ).

There will be a complicated updating this number. When you inserting node you have to update all heights on the path but no every one. Height always equal to max( left child height, right child height ) + 1. This inserting is recursive and I don't know if this is problem for you. Also during balancing you have to update heights and probably again with recursion.

I hope that this helps you. If not please specify the problem with recursion - time, memory, ... and we can try to find better solution

Upvotes: 2

Anna
Anna

Reputation: 4159

You can save the balance factor as a part of the information each node saves. Specifically, you can save the height of the left and right subtrees, and update the values with every insertion/deletion on the insertion/deletion path.

Example:

class Node {
  public:
    // stuff...
    int GetBF() { return lHeight - rHeight; }
  private:
    int data;
    Node* right;
    Node* left;
    Node* parent; // optional...
    int rHeight;  // Height of the right subtree
    int lHeight;  // Height of the left subtree
};

Upvotes: 8

Related Questions