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: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.