假設「訪問次數」是您想要按順序遍歷打印的節點數。一種解決方法是使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);
}
}
充分利用'inorder'函數返回一個表示左節點的數目,然後通過數作爲參數來'inorder'。 – nhahtdh 2013-04-10 01:51:03