简体   繁体   中英

Find a vertex of size k in an AVL tree

Let a be an AVL tree with n vertices. Each vertex has an extension representing the size of its sub-tree with the vertex himself as a root. I'm trying to implement an algorithm that gets as input a number k st 1<=k<=n and return a vertex of size k in O(logn).

If the tree is a full binary tree it's easy we can just go right/left until we reach the node with the size we need since all nodes in a height h will have the same size. But when the tree is not full i'm getting stuck.

Any help will be much appreciated.

Thanks in advance!

PS I assume that each vertex has a different value.

First you check if the left sub-tree is bigger than k, if it is -> continue searching in it. Otherwise, check if the left sub tree's size + 1 equals k, in that case the current element is the kth so return the current node. If we've reached this point it means that the the kth element will be in the right sub-tree, so move on to the right sub-tree and search for the k - (left sub tree size + 1) element, since we've eliminated all those nodes already.

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