繁体   English   中英

如何在BST中找到小于或等于给定值的节点数? (AVL TREE)

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

所以我需要编写一个获取BST根的递归函数和另一个k参数,我需要在BST中找到小于或等于k的节点数。 有任何想法吗? 谢谢我尝试了这个功能,但它没有真正起作用(仅适用于树中最小的5个节点)

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;
}

暂无
暂无

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

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