Calculating the balance factor of a node in avl tree

試著忘記壹切 提交于 2019-12-12 04:32:10

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/1979335/calculating-the-balance-factor-of-a-node-in-avl-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!