BST最小(C)

时间:2013-12-09 14:03:37

标签: 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
}

1 个答案:

答案 0 :(得分:1)

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没有负值,因此使用负值表示无效条件。

相关问题