How to augment an AVL tree?

為{幸葍}努か 提交于 2021-02-16 20:59:34

问题


I want to augment an avl tree to add extra properties to each node such as number of nodes it contains (i.e. in its subtree).

From this avl java implementation code here http://www.blackbam.at/blackbams-blog/2012/05/04/avl-tree-implementation-in-java/ I want to add certain code to it, so that each node will contain a size element.

In the AvlNode class, I changed it to:

/** Here is the AVL-Node class for Completenesse **/
public class AvlNode {
     public AvlNode left;
     public AvlNode right;
     public AvlNode parent;
     public int key;
     public int balance;
     public int size;

     public AvlNode(int k) {
          left = right = parent = null;
          balance = 0;
          key = k;
          size = 1;
     }
     public String toString() {
         return "" + key;
     }
}

But now for the AvlTree class, where do I actually add the code to update the size value of the node, during the insert and delete operations. I think it's the rotateleft and rotateright methods. Is this right?


回答1:


This completely depends on what you're trying to do with the augmentation. Typically, when augmenting a balanced binary search tree, you would need to insert extra code in the logic to do

  • Insertions, which change the number / contents of certain subtrees,
  • Deletions, which remove elements from subtrees, and
  • Tree rotations, which move nodes across different subtrees.

The "Introduction to Algorithms" textbook by CLRS has a chapter on augmented binary search trees. While they focus on red/black trees, the same general policies should work for any rotation-based tree balancing scheme.

Hope this helps!



来源:https://stackoverflow.com/questions/14740845/how-to-augment-an-avl-tree

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