假设“访问次数”是您想要从有序遍历中打印出来的节点数。一种解决方案是让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);
}
}