假设“访问次数”是您想要按顺序遍历打印的节点数。一种解决方法是使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