I found this in book:
Design a data structure for maintaining dynamic sequence x_1, x_2,... , x_n
which provides operations:
Insert(a,i) - inserts a as x_i, indexes from i+1 to n go up by 1
Delete(i) - deletes x_i, indexes from i+1 to n go down by 1
Find(i) - returns element x_i
Sum_even() - returns sum of the elements with even indexes
The sequence is dynamic so I want to use AVL tree to keep it. So I think I can use standard trick for find, delete and insert – just keep in each node size of sub tree rooted in this node. Then I can easily navigate the tree to find ith element in O(log n) time. Inorder gives me then: x_1, x_2,…, x_n.
But for Sum_even() I probably should have also sum of elements with even and odd indexes in each node. Although it’s difficult to update while inserting or deleting. How should it work, can anyone help?
You don’t have to store size of subtree in a node. AVL tree stores only difference in heights of left and right subtree: -1, 0 or +1.
In order to easily maintain
sum_evenyou need to storesum_evenandsum_oddfor each node. It will be the sum of values on even/odd indexes for subtree.So each node will have variables:
differencedifference in height of left and right subtreesvalueparityparity of subtree size (0 or 1)sum_evensum_oddFor inserts and deletes use standard algorithm http://en.wikipedia.org/wiki/AVL_tree.
But for each affected node (nodes on the way up to root and rotated nodes) update values: