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

标签 c data-structures struct binary-search-tree 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;
}

关于c - 如何找到 BST 中小于或等于给定值的节点数? (AVL 树),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55797383/

相关文章:

c - 显示突然行为的全局变量

c - 了解 C malloc 和 sbrk()

java - Java中的泛型是什么?

c - 关于C中返回函数的问题

c - 用 C 将结构写入文件的可移植方法是什么?

c - 使用超出预期内存使用量的大型 mmap 调用是否会产生性能成本?

r - 如何在 R 中正确使用列表?

java - 用于插入有序 vector 的左/右移位

c - 将数据存储在头文件中包含数组的 Stucts 中

c - 为什么 typedef 名称在 C 的结构声明中使用了两次?