# Finding rank of newly inserted node in AVL tree augmented with rank of node

My prof was talking about how to augment a tree to efficiently find the key with a given rank. On the way to getting the right answer (store the size of the subtree rooted at each node), he proposed augmenting each node with it's rank. That way finding the node with a certain rank is a simple binary search. But he said this wouldn't work because insertion would be $$\Theta(n)$$. I understand that this is because in the worst case the newly inserted node has rank 0 and so the rank of each node in the tree must be incremented by 1. What I am interested in knowing is an algorithm for computing the rank of a newly inserted node. At first I thought that if a node $$n$$ is inserted to the left of a leaf $$l$$ with rank $$k$$ then the rank of $$n$$ is $$k-1$$, or $$k+1$$ if inserted right of $$l$$. I found a counter example to that so I know it is not the case. So how would this be done?

• Hint: Insertion costs $O(\log n)$, so you can use $O(\log n)$ time for "free" – lox Jun 23 at 8:24
• Hint 2: after insertion of $x$, you have its left subtree (or null), right subtree (or null), and up to $log(n)$ nodes in the path from the root to $x$. – lox Jun 23 at 8:25
• On the path down to x from the root I keep track of the largest rank of any node smaller than x. Once x is inserted it's rank is 1 larger than the maximum. On my way back up to the root I update the rank of any node larger than me by adding 1 to it. Is this the correct answer? – nakamin Jun 23 at 15:13