简体   繁体   English

在AVL树中找到大小为k的顶点

[英]Find a vertex of size k in an AVL tree

Let a be an AVL tree with n vertices. 设a为具有n个顶点的AVL树。 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). 我正在尝试实现一种算法,该算法获得输入数k st 1 <= k <= n并返回O(logn)中大小为k的顶点。

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. 如果树是完整的二叉树,我们很容易就可以左右移动,直到我们到达所需大小的节点为止,因为高度为h的所有节点都将具有相同的大小。 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. PS我假设每个顶点都有不同的值。

First you check if the left sub-tree is bigger than k, if it is -> continue searching in it. 首先,检查左子树是否大于k,如果大于->继续在其中搜索。 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. 否则,检查左子树的大小+ 1是否等于k,在这种情况下,当前元素为第k个,因此返回当前节点。 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. 如果达到这一点,则意味着第k个元素将位于右侧子树中,因此请移至右侧子树并搜索k-(左侧子树大小+ 1)元素,因为已经消除了所有这些节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM