简体   繁体   中英

AVL tree : adding a new field to each node : the “size” of its tree , while Insert action

I'm trying to update the Insert action while inserting a new element into an AVL tree . The update to the insert action will add to each node the size of its rooted tree .

Now ,since I insert my elements bottom-up , then if I just add a +1 for every node that I pass while touring up , then in some cases this wouldn't work , for example when I need to balance the tree after the new tree is not balanced , since I change pointers , then the calculation wouldn't be correct .

Any idea or hint how can I do that correctly?

A simple solution could be to modify it simply with the definition of the size.

Give the leaves size = 1 , and for each node that is a part of the tour to the root, or was a part of a roll (from buttom up) set:

size(v) = size(v.left) + size(v.right) + 1
            ^                 ^          ^
        size of left     size of right   size of "root"
           subtree        subtree     

This will be correct because you modify in each step all the vertices that were changed, and since you do it buttom-up, the size can be calculated correctly for each node you modify.

Note that it does not affect complexity, since for each such vertex - you are doing constant number of OPs, and you are doing it only to vertices you would have traversed anyway.

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