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.
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
};
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