简体   繁体   English

在AVL树中找到第k个最小节点

[英]Find kth min node in AVL tree

I now have built a AVL tree, Here is a function to find kth min node in AVL tree (k started from 0) Code: 我现在已经建立了一个AVL树,这是一个在AVL树中找到第k个最小节点的函数(k从0开始)代码:

int kthMin(int k)
{
    int input=k+1;
    int count=0;
    return KthElement(root,count,input);
}

int KthElement( IAVLTreeNode * root, int count, int k)
{
    if( root)
    {
        KthElement(root->getLeft(), count,k);
        count ++;
        if( count == k)
            return root->getKey();
        KthElement(root->getRight(),count,k);
    }
    return NULL;
}

It can find some of right nodes, but some may fail, anyone can help me debug this> THanks 它可以找到一些正确的节点,但是某些节点可能会失败,任何人都可以帮助我调试此>

From the root, after recursing left, count will be 1, regardless of how many nodes are on the left. 从根开始,向左递归后,无论左边有多少个节点, count都将为1。

You need to change count in the recursive calls, so change count to be passed by reference (assuming this is C++). 您需要更改count的递归调用,所以改变count被引用传递(假设这是C ++)。

int KthElement( IAVLTreeNode * root, int &count, int k)

(I don't think any other code changes are required to get pass by reference to work here). (我认为不需要其他任何代码更改即可通过引用通过此处工作)。

And beyond that you need to actually return the value generated in the recursive call, ie change: 除此之外,您还需要实际返回递归调用中生成的值,即更改:

KthElement(root->getLeft(), count, k);

to: 至:

int val = KthElement(root->getLeft(), count, k);
if (val != 0)
   return val;

And similarly for getRight . 同样对于getRight

Note I used 0 , not NULL . 注意我使用的是0 ,而不是NULL NULL is typically used to refer to a null pointer, and it converts to a 0 int (the latter is preferred when using int ). NULL通常用于引用空指针,并将其转换为0 int (使用int时首选后者)。

This of course assumes that 0 isn't a valid node in your tree (otherwise your code won't work). 当然,这假定0不是树中的有效节点(否则您的代码将无法工作)。 If it is, you'll need to find another value to use, or a pointer to the node instead (in which case you can use NULL to indicate not found). 如果是这样,则需要找到另一个要使用的值,或者改为指向该节点的指针(在这种情况下,可以使用NULL表示未找到)。

Here is simple algorithm for Kth smallest node in any tree in general:- 通常,这是任何树中第K个最小节点的简单算法:-

count=0, found=false;

kthElement(Node p,int k) {

    if(p==NULL)
        return -1

    else {

        value = kthElement(p.left)             
        if(found)
            return value 

        count++
        if(count==k) {
            found = true
            return p.value
        }

        value = kthElement(p.right)
        return value
    }
}

Note:- Use of global variables is the key. 注意:-使用全局变量是关键。

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

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