我必须编写一个函数来查找第一个子级 - 下一个同级 N 叉树的级别中的节点数。 我的职能是:
int nodesAtLevel(NTree root, int level) {
if (root == NULL) {
return 0;
}
if (level == 0) {
return 1;
}
return nodesAtLevel(root->firstChild, level - 1) +
nodesAtLevel(root->nextSibling, level - 1);
}
但是它不起作用。 有人可以帮助我吗?
最佳答案
现在,您的代码似乎只返回 2。我相信这就是您想要做的:
int nodesAtLevel(NTree root, int level) {
if (root == NULL) {
return 0;
}
if (level == 0) {
return 1;
}
int x = nodesAtLevel(root->firstChild, level - 1);
int y = nodesAtLevel(root->nextSibling, level - 1);
return x + y + 1; //add 1 for current node
}
与当前代码不同,这应该在每次递归后更新值。
关于c - 第一个子级 - 下一个兄弟树中某个级别的节点数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347068/