用C中的二进制搜索树查找总数

时间:2018-02-21 03:15:56

标签: c recursion binary-search-tree

让我说我有BST

          50
         /  \
        30   70
       / \   / \
      20 40 60 80

我的总深度应为1 + 2 + 2 + 3 + 3 + 3 + 3 = 17,我有总深度功能

int Total_Depth(struct node* node, int depth){
if (node==NULL){
    return 0;}
else{
    return depth + Total_Depth(node->left, depth++) + Total_Depth(node->right, depth++);
}

当我在main()printf("%d\n", Total_Depth(root, 0))中调用Total_Depth函数时,我得到12而不是17.有人可以解释为什么会这样吗?我无法找到找到总深度的方法

1 个答案:

答案 0 :(得分:2)

使用后增量深度++ 调用递归函数。 后增量运算符在使用后递增变量,因此它只会在返回递归函数后递增变量。 为此,在递归函数调用中,您不应该使用post-increment。

因此,您应该用深度+ 1 替换深度++

  return depth + Total_Depth(node->left, depth+1) + 
  Total_Depth(node->right, depth+1);