计算BST离开C

时间:2014-02-07 20:05:11

标签: 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;
}

1 个答案:

答案 0 :(得分: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,但你应该得到算法的想法。

相关问题