计算 C 上的 BST 级别

标签 c binary-search-tree

有一种递归方法来计算级别,这很相似,但不起作用。我的错误是哪一个?

struct s_node
{
  struct s_node * left;
  struct s_node * right;
  int value;
}
typedef struct s_node * t_node;
int levels (t_node tree)
{
  if(tree != NULL)
  {
    return 1+levels(tree->left)+levels(tree->right);
  }
  else
       return 0;
}

最佳答案

这会计算节点总数。如果您想“计算级别”(我假设这意味着您想确定树的高度),您可以将代码修改为如下所示:

int max(int a, int b)
{
    if (a > b)
        return a;
    return b;
}

int levels (struct s_node * tree)
{
    if (tree != NULL)
    {
        return 1 + max(levels(tree->left), levels(tree->right));
    }
    else 
        return 0;
}

请注意,其中可能仍然存在 C 错误,我已经很多年没有使用 C 了,但是您应该了解算法的想法。

关于计算 C 上的 BST 级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21636788/

相关文章:

c - 如何使用xcode使用相对路径在C中打开文件?

c - C中空结构的大小是多少?

C++ 程序使用 C 库中的损坏符号导致 undefined symbol

ruby - 骑士的艰辛和二叉搜索树

java - 二叉搜索树 - 删除所有大于特定值的整数

python - Python 类 二叉搜索树

c - 将数组写入文本文件

c# - 如何在 c# (mono) 中导入 c 库 (.dll/.so)

algorithm - 适用于事件日历应用程序的最佳数据结构

c - 二叉树和 printf 的奇怪错误