views:

587

answers:

2

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.

+5  A: 

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
};
Anna
Point for you, you are quicker. I was writing my solution too long time but we have got same idea. But I think that in this solution will require recursive update during inserting and it can be problem because in requirements is "without recursion"
Gaim
@Gaim, In any case, the insertion in an AVL tree needs to go over all of the nodes in the insertion path. It doesn't matter if you write a recursive or an iterative function for that (recursive one would be easier to implement, though). These nodes are the only ones whose balance factor changes, so the rHeight and lHeight would be updated then. If you have a specific node at hand - the calculation of the balance factor is done in O(1).
Anna
+2  A: 

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

Gaim