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

问题描述 投票:0回答:1

所以我需要编写一个获取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;

}

c data-structures struct binary-search-tree avl-tree
1个回答
0
投票
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.