返回二进制搜索树的平均深度的函数

时间:2015-06-10 08:50:00

标签: c algorithm tree binary-tree binary-search-tree

我有以下二叉树结构,我想编写一个函数来计算并返回树中对象的平均深度。 这是我正在尝试做的事情:

  • 计算树的总高度
  • 划分总高度/总节点数

但是,我无处可去,并希望在如何实施算法方面提供任何有用的建议。

typedef struct tree_s tree_t;
struct tree_s {
    int num;
    tree_t *left;
    tree_t *right;
}


int total_depth(tree_t *tree, int accum) {
    if (tree == NULL) {
        return accum; /* done */
    }
    accum = accum + total_depth(tree->left, accum+1);
    accum = accum + total_depth(tree->right, accum+1);
    return accum;
}

我的递归函数total_depth似乎有问题,因为我得到了一个非常大的数字。

1 个答案:

答案 0 :(得分:2)

你应该做的事情如下:

int total_depth(tree_t *tree, int accum)
{
    if (tree == NULL) {
        return 0;
    }
    return accum +
        total_depth(tree->left, accum + 1) +
        total_depth(tree->right, accum + 1);
}

total_depth(root, 0);