c - BST 第 n 个最小 (C)

标签 c binary-tree binary-search-tree

此函数尝试查找 BST 中第 n 个最小的数。我知道这本质上只是一个计数器的有序遍历。如果是这样,那么为什么这段代码不起作用?

假设我的 BST 已正确实现(事实确实如此),为什么它会打印出 9?它应该打印出 6。

int bst_ith_smallest(BST_PTR t, int i)
{
    if(i > count)
        fprintf(stderr, "Input is greater than BST size");

    return (smallest_helper(t->root, i));
}


int smallest_helper(NODE *r, int i)
{
    if(r==NULL) 
        return;

    smallest_helper(r->left, --i);

    if(i == 0)
        return r->val;

    smallest_helper(r->right, --i);
}


My test function:

int main()
{
  int i;

  int a[] = {8, 2, 7, 9, 11, 3, 2, 6};


  BST_PTR t = bst_create();

  for(i=0; i<8; i++)
    bst_insert(t, a[i]);

  printf("%d\n", bst_ith_smallest(t, 3)); <------ HERE the function is called
  //other tests here
}

最佳答案

smallest_helper 代码中存在两个问题:您应该仅在访问节点时递减计数器,并且应该传播返回值。另外,当函数应该返回值时,请注意没有值的 return

试试这个:

int smallest_helper(NODE *r, int i)
{
    if (r == NULL) {
        return -1;
    }
    int val;
    val = smallest_helper(r->left, i);
    if (val >= 0) {
        return val;
    }
    if (--i == 0) {
        return r->val;
    }
    val = smallest_helper(r->right, i);
    if (val >= 0) {
        return val;
    }
    return -1;
}

假设您的 BST 没有负值,因此负值用于指示无效条件。

关于c - BST 第 n 个最小 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20472545/

相关文章:

c - 从 poll() 添加/删除套接字描述符

c - 为什么这个指针运算不起作用?

c - 使用C在排序数组中大于给定数字的最小数字的数组索引

c++ - 打印 BST 最小-最大

C 程序错误 - 段错误(核心已转储)

c - Lua 和 C 语言的 NGINX 模块

c - 在 C 程序中使用 0 而不是 '\0'

c++ - 在简单的 Leftist Heap Insert 的结果方面需要帮助

c++ - 二叉树中的水平顺序插入

c++ - 二叉搜索树验证的空间复杂度