简体   繁体   中英

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:

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.

You need to change count in the recursive calls, so change count to be passed by reference (assuming this is 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 .

Note I used 0 , not 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 ).

This of course assumes that 0 isn't a valid node in your tree (otherwise your code won't work). 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).

Here is simple algorithm for Kth smallest node in any tree in general:-

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.

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