简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM