简体   繁体   English

计算avl树中节点的平衡因子

[英]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. 我想在不使用任何递归过程的情况下计算avl树中节点的平衡因子。 How can i do that? 我怎样才能做到这一点? Please tell me method or provide C++ code snippet. 请告诉我方法或提供C ++代码段。

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 ). 然后您可以在恒定时间内获得平衡因子(左右孩子的身高之差,如果child为NULL则height为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. 高度始终等于max(左子高度,右子高度)+1。此插入是递归的,我不知道这是否对您有问题。 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 如果不是,请指定递归问题-时间,内存等,我们可以尝试找到更好的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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