2013-04-10 101 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); 
    } 
}