【发布时间】:2018-12-07 11:27:46
【问题描述】:
我试图在递归函数中索引一个数组,但是索引没有按预期工作,因为我无法在函数内增加一个计数器。问题可以简化为以下代码。
这里的根是一个指向节点结构的指针,它是一个简单的树。
递归函数:
void inorder(node *root, int in_count)
{
if (root != NULL)
{
inorder(root->left, in_count);
printf("key is %d and count is %d\n", root->KEY, root->node_count, in_count++);
//index array arr[in_count];
inorder(root->right, in_count);
}
}
主要:
int main()
{
int in_count =0;
printf("Inorder traversal of the given tree \n");
inorder(root, in_count);
}
输出:
Inorder traversal of the given tree
key is 1 and count is 0
key is 2 and count is 0
key is 2 and count is 1
key is 2 and count is 2
key is 3 and count is 0
key is 5 and count is 1
key is 7 and count is 2
key is 9 and count is 3
key is 12 and count is 0
我预计 in_count 会从 0 增加到 8,但事实并非如此。为什么计数会重置?任何建议将不胜感激。
【问题讨论】: