简体   繁体   中英

How can I find the number of nodes that are smaller or equal to a given value in BST? (AVL TREE)

so I need to write a recursive function that gets the BST root and a another parameter that is k, and I need to find the number of nodes that are smaller or equal to k in the BST. Any Ideas? Thanks I tried this function but it didn't really work (worked only for the smallest 5 nodes in tree)

int avl_rank( AVLNodePtr tnode, int k )

if (tnode == NULL)
    return 0;

int count = 0;

// if current root is smaller or equal
// to x increment count
if (tnode->key <= k)
    count++;

// Number of children of root
int numChildren;
if (tnode->child[0]==NULL && tnode->child[0]==NULL)
    numChildren = 0;
else if ((tnode->child[0]!=NULL && tnode->child[0]==NULL) || (tnode->child[0]==NULL && tnode->child[0]!=NULL))
    numChildren = 1;
else numChildren = 2;

// recursively calling for every child
int i;
for ( i = 0; i < numChildren; i++)
{
    AVLNodePtr child = tnode->child[i];
    count += avl_rank(child, k);
}

// return the count
return count;

}

int avl_rank( AVLNodePtr tnode, int k )
{
    if(tnode==NULL) return 0;
    int count = 0;
    if (tnode->key<=k) count++;
        count += (avl_rank(tnode->child[0],k) +
            avl_rank(tnode->child[1],k));
    return count;
}

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