有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java正确删除三元搜索树中的节点

我想使用三元搜索树中的键删除特定节点。这在大多数情况下都非常有效,但在我的一些测试集中,没有中间子节点的节点也不存储值,这是不应该发生的

我尝试了我在网上找到的不同方法,但几乎所有这些方法都让树处于脏状态,这使得搜索变得很麻烦,因为你需要检查你找到的叶子是否真的有值,这是不应该发生的

这是我的相关代码

private boolean hasChildren(Node x) {
    return (x.left != null || x.mid != null || x.right != null);
}

private void reHang(Node x) {
    if (hasChildren(x)) {
        if (x.left != null) {
            x.parent.mid = x.left;
            x.left.right = x.right;
        } else if (x.right != null) {
            x.parent.mid = x.right;
        }
    }
}

private boolean remove(Node x, String key, int d) {
  if (x == null) return false;
  char c = key.charAt(d);
  if (c < x.c) {
      if (!remove(x.left, key, d)) {
          x.left = null;
      }
  } else if (c > x.c) {
      if (!remove(x.right, key, d)) {
          x.right = null;
      }
  } else if (d < key.length() - 1) {
      if (!remove(x.mid, key, d + 1)) {
          x.mid = null;
          if (x.val != null) return true;
      }
  } else {
      x.val = null;
  }

  reHang(x);
  return hasChildren(x);
}

private class Node
{
    private Value val;
    private char c;
    private Node left, mid, right, parent;
}

具体而言,我用于前缀查找的函数中会出现问题:

private Node getMidPath(Node x) {
    if (x.left != null) return getMidPath(x.left);
    if (x.mid == null) return x;
    return getMidPath(x.mid);
}

每个没有x.mid的节点都应该有一个x.val集,这在移除后并不总是如此,这意味着我有脏节点

任何帮助都将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    你们必须看到一个三元树:一些嵌套的二元树,但每一级只有一个字符作为键,而不是整个字符串。沿着二叉树往下走,直到字符串用尽为止。这里有两个最终引用,一个引用实际数据,另一个引用实际子树,用于前缀相同的较长字符串。现在将数据设置为null。当子树引用为null时,删除节点。现在,整个子树为空时,请将子树提前一个字符继续。这里将子树引用设置为null。现在是两个引用都为null删除节点。现在,整个子树为空时,请将子树提前一个字符继续。等等