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

标签 c data-structures tree n-ary-tree

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

相关文章:

c - C 编程语言练习 1 - 13

c - Arch Linux 上的 AVR

java - 哪种列表实现最适合从前面和后面删除和插入?

具有真实示例的 Angular Material 树复选框

c++ - C++中使用引用的二叉树

c++ - 如何从节点的父节点列表构建树?

c - epoll 立即返回标准输入

algorithm - 存储二维区间的数据结构

ios - 如何正确构建 Firebase 数据库?

c - 二叉搜索树和结构错误