gpt4 book ai didi

c - 第一个子级 - 下一个兄弟树中某个级别的节点数

转载 作者:行者123 更新时间:2023-11-30 16:43:20 26 4
gpt4 key购买 nike

我必须编写一个函数来查找第一个子级 - 下一个同级 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com