【问题标题】:Find depth of a specific node in BST in C在C中查找BST中特定节点的深度
【发布时间】:2021-01-30 15:53:15
【问题描述】:

假设以下树按顺序排列:2、9、4、7。我需要找到每个节点的深度:节点 2 - 深度 0,节点 9 - 深度 1,节点 4 - 深度 2,节点 7 - 深度 3 .

2
 \
  9
 /
4
 \
  7

但是,我得到的输出是:节点 2 - 深度 0,节点 9 - 深度 -1,节点 4 - 深度 -1,节点 7 - 深度 -1。

我认为我无法遍历右子树,因为 left 每次都大于零,并且函数在到达右侧之前退出。但我不确定如何修复代码以产生正确的输出。

我的代码:

int findDepth(Tree t, int key, int depth) {

    if (t == NULL) {
        return -1; 
    }

    if (t->value == key) {
        return depth;
    }

    int left = findDepth(t->left, key, depth + 1);
    if (left != 0) {
        return left; 
    }

    int right = findDepth(t->right, key, depth + 1); 
    if (right != 0) {
        return right; 
    }

    return 0; 

}

int treeNodeDepth(Tree t, int key) {

    return findDepth(t, key, 0);

}

【问题讨论】:

    标签: c


    【解决方案1】:

    当有节点和没有节点时,你都调用int left = findDepth(t->left, key, depth + 1);。两者都可以,但如果你用NULL 打电话,你应该更新测试

       if (left != 0) {
            return left; 
        }
    

    所以当-1 从子树收到时你不会返回。

    选项一,调用前测试:

    if (t->left){
        int left = findDepth(t->left, key, depth + 1);
        if (left != 0) {
            return left; 
        }
    }
    

    选项二改变测试:

    int left = findDepth(t->left, key, depth + 1);
    if (left > 0) {
        return left; 
    }
    

    第三种选择是更改 Nullpointers 的返回值,以匹配上面的测试。

    if (t == NULL) {
        return 0; 
    }
    

    【讨论】:

      【解决方案2】:

      问题来了

       int left = findDepth(t->left, key, depth + 1);
      if (left != 0) {
          return left; 
      }
      

      假设您搜索 9,但是当您进入根目录(即 2)时,由于上面的代码,它会检查左侧并返回 -1,因为 2 的左侧为空,而您返回 -1 为空。由于 -1 不等于 0 此代码将返回 -1 而不是 9 的正确位置。 对此有多种修复,但我将把它留给你。如果您仍然不知道如何解决它,请发表评论,我会提供一些选项

      【讨论】:

        猜你喜欢
        • 2021-12-02
        • 2014-12-15
        • 1970-01-01
        • 2020-07-24
        • 1970-01-01
        • 1970-01-01
        • 2012-11-03
        • 2016-10-24
        • 1970-01-01
        相关资源
        最近更新 更多