代码之家  ›  专栏  ›  技术社区  ›  Dongho Han

用C语言中的二叉搜索树查找合计

  •  0
  • Dongho Han  · 技术社区  · 8 年前

    假设我有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()中调用Total\u Depth函数时 printf("%d\n", Total_Depth(root, 0)) 我得到12分,而不是17分。谁能解释一下为什么会这样?我真的想不出一个方法来找到总深度

    1 回复  |  直到 8 年前
        1
  •  2
  •   Md. Mostafizur Rahman    8 年前

    使用post增量调用递归函数 深度++ . post increment操作符在使用变量后对其进行递增,因此它只会在递归函数返回后对变量进行递增。 为此,在递归函数调用中,不应使用后增量。

    所以,你应该更换你的 深度++ 具有 深度+1 .

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