2013-04-10 100 views
0

我知道這可能是一個簡單的問題,但是我已經完成了任何C編程已經有一段時間了。我正嘗試在x節點上執行一個inorder遍歷,其中x是我傳遞給該函數的一些數字。我的inorder函數遞歸地調用自己,並且爲了我的生活,我無法知道如何在拜訪x節點後停止遍歷。這裏是我的inorder遍歷函數:遍歷x中的節點數

void inorder(node h) 
{ 

    if (h != NULL) 
    { 
     inorder(h->l); 

     printf(" %d\n",h->item); 

     inorder(h->r); 
    } 
     return; 

} 

任何指導,非常感謝。

+0

充分利用'inorder'函數返回一個表示左節點的數目,然後通過數作爲參數來'inorder'。 – nhahtdh 2013-04-10 01:51:03

回答

0

嘗試此操作 - 應僅適用於訪問的x個節點(其中訪問的節點數是要打印的候選節點);

int inorder(node h, int x) 
{ 

    if (h != NULL && x > 0) 
    { 
     x = inorder(h->l, x); 

     if (x > 0) { 
      printf(" %d\n",h->item); 
      x--; 
     } 
     if (h->r && x > 0) 
      x = inorder(h->r, x); 
    } 
     return x; 

} 

[EDIT:該代碼是由@nhahtdh後訪問的節點的定義和遞減x的值的一些討論校正。工作測試代碼可見here

+0

x是他想要訪問的元素,而不是按順序訪問深度,我認爲 – MYMNeo 2013-04-10 02:04:42

+0

我認爲如果我沒有看到問題錯誤,他想訪問x個節點。 – nommyravian 2013-04-10 02:05:28

+0

我認爲你減少太多。你只應該減少一次,但似乎你每遞減一次函數調用x次(忽略遞歸調用)。 – nhahtdh 2013-04-10 02:22:12

1

假設「訪問次數」是您想要按順序遍歷打印的節點數。一種解決方法是使inorder函數返回剩餘要打印的節點數,並在遍歷樹時檢查它。

int inorder(node h, int x) 
{ 
    // I mimic your current code. The code is indeed shorter, but it will 
    // do extra recursion, compared to the other approach of checking 
    // for the subtree and value of x before the recursive call. 
    if (h != NULL && x > 0) 
    { 
     x = inorder(h->l, x); 

     if (x > 0) { 
      printf(" %d\n",h->item); 
      x--; 
     } 

     x = inorder(h->r, x); 
    } 

    return x; 
} 

在另一個實施細微變化是將指針傳遞到包含x的變量,並用它來更新計數器。如果以這種方式寫的話,函數不需要返回任何東西。

void inorder(node h, int *x) 
{ 
    // I mimic your current code. The code is indeed shorter, but it will 
    // do extra recursion, compared to the other approach of checking 
    // for the subtree and value of x before the recursive call. 
    if (h == NULL && *x > 0) 
    { 
     inorder(h->l, x); 

     if (*x > 0) { 
      printf(" %d\n",h->item); 
      (*x)--; 
     } 

     inorder(h->r, x); 
    } 
}