【问题标题】:Deleting the maximum element in BST删除 BST 中的最大元素
【发布时间】:2017-07-12 08:18:05
【问题描述】:

下面的一些代码似乎太明显了,使用它最右边的分支遍历树,因为这是所有最大值所在的地方。但是,我不明白我在 Robert Sedgewick 的算法书中看到的关于这段代码的一些事情.

     public void deleteMax() {
     if (isEmpty()) throw new NoSuchElementException("");
     root = deleteMax(root);
     assert check();
     }

    private Node deleteMax(Node x) {
    if (x.right == null) return x.left;
    x.right = deleteMax(x.right);
    x.size = size(x.left) + size(x.right) + 1;
    return x;
    }

在私有方法中,如果 x 的右孩子为 null,为什么我们返回左元素?据我了解,如果 x 没有右孩子并且是我们可以去的最右边的节点,那么 x 将是最大值。另外我不明白我们什么时候在第二个方法的最后一行返回 x。

【问题讨论】:

    标签: binary-search-tree


    【解决方案1】:

    如果x 没有右孩子,那么x 是最大节点。我们通过返回x.left(新的最大节点)来“删除”它。修改右子树后返回x

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      相关资源
      最近更新 更多