簡體   English   中英

BST最小(C)

[英]BST nth smallest (C)

此函數嘗試查找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沒有負值,因此負值用於表示無效條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM