【问题标题】:Red Black Tree Top-Down Deletion Algorithm红黑树自顶向下删除算法
【发布时间】:2012-12-16 16:46:22
【问题描述】:

我正在 O (log n) 时间内实现具有插入、搜索和删除功能的红黑树。插入和搜索工作正常。但是我被困在删除上。我在互联网上找到了这张显示 RBT 删除算法的 ppt 幻灯片:http://www.slideshare.net/piotrszymanski/red-black-trees#btnNext 在第 56 页起。我知道我的要求有点过分,但我已经坚持了两个多星期,我找不到问题所在。我理解自上而下删除的方式是,您必须相应地旋转和重新着色节点,直到找到要删除的节点的前身。当你确实找到了这个节点——它可能是一个叶子节点或者一个有一个右孩子的节点,用这个节点的数据替换要删除的节点数据,然后像正常的 BST 删除一样删除这个节点,对吧?

这是我根据从幻灯片中学到的内容编写的代码。如果有人能这么好心地检查一下,我将不胜感激!或者至少如果你认为有比我使用的更好的算法,请告诉我!

 public void delete(int element){

    if (root == null){ 
        System.out.println("Red Black Tree is Empty!");

    } else {

      Node X = root; 
      parent = null; 
      grandParent = null; 
      sibling = null; 

      if (isLeaf(X)){

          if (X.getElement() == element){
              emptyRBT();
          } 

      } else {

      if (checkIfBlack(root.getLeftChild()) && checkIfBlack(root.getRightChild())){
          root.setIsBlack(false);

          if (X.getElement() > element && X.getLeftChild() != null){ 
              X = moveLeft(X);

          } else if (X.getElement() < element && X.getRightChild() != null){
              X = moveRight(X);
          } 

          Step2(X, element);

      } else { 

          Step2B(X, element);

       } 
     }
   } 
   root.setIsBlack(true);
}

public void Step2(Node X, int element)
{
    int dir = -1;

    while (!isLeaf(X)){

      if (predecessor == null){  // still didn't find Node to delete

        if (X.getElement() > element && X.getLeftChild() != null){
            X = moveLeft(X);
            dir = 0;
        } else if (X.getElement() < element && X.getRightChild() != null){
            X = moveRight(X);
            dir = 1;
        } else if (X.getElement() == element){
            toDelete = X;
            predecessor = inorderPredecessor(X.getRightChild());
            X = moveRight(X);
        }

      } else { // if node to delete is already found and X is equal to right node of to delete
               // move always to the left until you find predecessor

          if (X != predecessor){
              X = moveLeft(X);
              dir = 0;
          } 
      }

      if (!isLeaf(X)){
        if (!hasOneNullNode(X)){

         if (checkIfBlack(X.getLeftChild()) && checkIfBlack(X.getRightChild())){
             Step2A(X, element, dir);
         } else {
             Step2B(X, element);
         }
       }
     }
   }

   removeNode(X);

   if (predecessor != null){
       toDelete.setElement(X.getElement());
   }
}

public Node Step2A(Node X, int element, int dir) {

    if (checkIfBlack(sibling.getLeftChild()) && checkIfBlack(sibling.getRightChild())) {
        X = Step2A1(X);

    } else if ((checkIfBlack(sibling.getLeftChild()) == false) && checkIfBlack(sibling.getRightChild())) {
        X = Step2A2(X);

    } else if ((checkIfBlack(sibling.getLeftChild()) && (checkIfBlack(sibling.getRightChild()) == false))) {
        X = Step2A3(X);

    } else if ((checkIfBlack(sibling.getLeftChild()) == false) && (checkIfBlack(sibling.getRightChild()) == false)) {
        X = Step2A3(X);
    }

    return X;
}

public Node Step2A1(Node X) {

    X.setIsBlack(!X.IsBlack());
    parent.setIsBlack(!parent.IsBlack());
    sibling.setIsBlack(!sibling.IsBlack());

    return X;
}

public Node Step2A2(Node X) {

    if (parent.getLeftChild() == sibling){
        LeftRightRotation(sibling.getLeftChild(), sibling, parent);

    } else RightLeftRotation(sibling.getRightChild(), sibling, parent);

    X.setIsBlack(!X.IsBlack());
    parent.setIsBlack(!parent.IsBlack());

    return X;
}

public Node Step2A3(Node X) {

    if (parent.getLeftChild() == sibling){
        leftRotate(sibling);
    } else if (parent.getRightChild() == sibling){
        rightRotate(sibling);  
    }

    X.setIsBlack(!X.IsBlack());
    parent.setIsBlack(!parent.IsBlack());
    sibling.setIsBlack(!sibling.IsBlack());
    sibling.getRightChild().setIsBlack(!sibling.getRightChild().IsBlack());

    return X;
}

public void Step2B(Node X, int element){

    if (predecessor == null){
        if (X.getElement() > element && X.getLeftChild() != null){
            X = moveLeft(X);
        } else if (X.getElement() < element && X.getRightChild() != null){
            X = moveRight(X);
        } else if (X.getElement() == element){
            Step2(X, element);
        }

    } else {

        if (X != predecessor)
            X = moveLeft(X);
        else Step2(X, element);
    }

    if (X.IsBlack()){

       if (parent.getLeftChild() == sibling){
           leftRotate(sibling);
       } else if (parent.getRightChild() == sibling){
           rightRotate(sibling);
       }

       parent.setIsBlack(!parent.IsBlack());
       sibling.setIsBlack(!sibling.IsBlack()); 

       Step2(X, element);

    } else {
        Step2B(X, element);
    }
}

public void removeNode(Node X) {

    if (isLeaf(X)) {
        adjustParentPointer(null, X);
        count--;

    } else if (X.getLeftChild() != null && X.getRightChild() == null) {
        adjustParentPointer(X.getLeftChild(), X);
        count--;

    } else if (X.getRightChild() != null && X.getLeftChild() == null) {
        adjustParentPointer(X.getRightChild(), X);
        count--;
    } 
}

public Node inorderPredecessor(Node node){

   while (node.getLeftChild() != null){
       node = node.getLeftChild();
   }

   return node;
}

public void adjustParentPointer(Node node, Node current) {

    if (parent != null) {

        if (parent.getElement() < current.getElement()) {
            parent.setRightChild(node);
        } else if (parent.getElement() > current.getElement()) {
            parent.setLeftChild(node);
        }
    } else {
        root = node;
    }
}

public boolean checkIfBlack(Node n){
    if (n == null || n.IsBlack() == true){
        return true;
    } else return false;
}

public Node leftRotate(Node n)
{  
    parent.setLeftChild(n.getRightChild());
    n.setRightChild(parent);

    Node gp = grandParent;

    if (gp != null){

        if (gp.getElement() > n.getElement()){
            gp.setLeftChild(n);
        } else if (gp.getElement() < n.getElement()){
            gp.setRightChild(n);
        }

    } else root = n;

    return n;
}

public Node rightRotate(Node n)
{  
    parent.setRightChild(n.getLeftChild());
    n.setLeftChild(parent);

    Node gp = grandParent;

    if (gp != null){

        if (gp.getElement() > n.getElement()){
            gp.setLeftChild(n);
        } else if (gp.getElement() < n.getElement()){
            gp.setRightChild(n);
        }

    } else root = n;

    return n;
}

节点正在被删除,但删除后的树会黑违,这是非常错误的。

【问题讨论】:

标签: java data-structures red-black-tree top-down


【解决方案1】:

快速链接: http://algs4.cs.princeton.edu/33balanced/RedBlackBST.java.html

--> 注意:网站上的代码依赖于两个 jars。然而,在数据结构中,依赖性可能很小。有时将 main 方法注释掉就足够了(仅用作测试客户端) 如果不是:可以在同一站点上下载这些 jar。

如果您正在寻找两周的时间并学习算法,那么您很可能会了解

http://algs4.cs.princeton.edu/

伴随着名的网站

算法,作者:Robert Sedgewick 和 Kevin Wayne

书。

在这个网站上,有一个红黑(平衡)树的实现:

http://algs4.cs.princeton.edu/33balanced/RedBlackBST.java.html

我还没有研究它(我将在今年晚些时候),但我完全相信它是一个 RBTree 的工作实现。

本主题的访问者可能会感兴趣的一些旁注: 麻省理工学院在网上开设了有关算法的优秀课程。关于 rbtrees 的一个是 http://www.youtube.com/watch?v=iumaOUqoSCk

【讨论】:

  • 感谢您的回答彼得。我已经熟悉你给我的网站,甚至麻省理工学院的讲座。但是,这些都是自下而上的实现,我需要了解自上而下的实现,因为我以这种方式执行插入功能,也因为我更熟悉自上而下的思维。我在互联网上到处寻找一种比我在问题中发布链接的算法更好的算法,但似乎自下而上更受欢迎!你觉得我的解释好吗?我真的看不出代码有什么问题..即使调试:/
【解决方案2】:

eternally confuzzled blog 具有自上而下的红黑树插入和删除实现。它还逐案讨论了它的工作原理。我不会在这里复制它(它相当冗长)。

我已将该博客用作在 c++ 和 java 中实现红黑树的参考。正如我在earlier answer 中讨论的那样,我发现该实现比 std::map 自下而上的红黑树实现要快(无论 STL 在当时 gcc 附带什么)。

这是一个未经测试的、直接将代码翻译成 Java 的代码。我强烈建议您对其进行测试并对其进行变形以匹配您的风格。

private final static int LEFT = 0;
private final static int RIGHT = 1;

private static class Node {
    private Node left,right;
    private boolean red;
    ...

    // any non-zero argument returns right
    Node link(int direction) {
        return (direction == LEFT) ? this.left : this.right;
    }
    // any non-zero argument sets right
    Node setLink(int direction, Node n) {
        if (direction == LEFT) this.left = n;
        else this.right = n;
        return n;
    }
}

boolean remove(int data) {
  if ( this.root != null ) {
    final Node head = new Node(-1, null, null); /* False tree root */
    Node cur, parent, grandpa; /* Helpers */
    Node found = null;  /* Found item */
    int dir = RIGHT;

    /* Set up helpers */
    cur = head;
    grandpa = parent = null;
    cur.setLink(RIGHT, this.root);

    /* Search and push a red down */
    while ( cur.link(dir) != null ) {
      int last = dir;

      /* Update helpers */
      grandpa = parent, parent = cur;
      cur = cur.link(dir);
      dir = cur.data < data ? RIGHT : LEFT;

      /* Save found node */
      if ( cur.data == data )
        found = cur;

      /* Push the red node down */
      if ( !is_red(cur) && !is_red(cur.link(dir)) ) {
        if ( is_red(cur.link(~dir)) )
          parent = parent.setLink(last, singleRotate(cur, dir));
        else if ( !is_red(cur.link(~dir)) ) {
          Node s = parent.link(~last);

          if ( s != null ) {
            if (!is_red(s.link(~last)) && !is_red(s.link(last))) {
              /* Color flip */
              parent.red = false;
              s.red = true;
              cur.red = true;
            }
            else {
              int dir2 = grandpa.link(RIGHT) == parent ? RIGHT : LEFT;

              if ( is_red(s.link(last)) )
                grandpa.setLink(dir2, doubleRotate(parent, last));
              else if ( is_red(s.link(~last)) )
                grandpa.setLink(dir2, singleRotate(parent, last));

              /* Ensure correct coloring */
              cur.red = grandpa.link(dir2).red = true;
              grandpa.link(dir2).link(LEFT).red = false;
              grandpa.link(dir2).link(RIGHT).red = false;
            }
          }
        }
      }
    }

    /* Replace and remove if found */
    if ( found != null ) {
      found.data = cur.data;
      parent.setLink(
        parent.link(RIGHT) == cur ? RIGHT : LEFT,
        cur.link(cur.link(LEFT) == null ? RIGHT : LEFT));
    }

    /* Update root and make it black */
    this.root = head.link(RIGHT);
    if ( this.root != null )
      this.root.red = false;
  }

  return true;
}

【讨论】:

  • 非常感谢@Michael ..你帮了很多忙!对其进行了测试并进行了一些更改,以便我以自己的方式更了解它,并且效果很好!不知道我在这里提交的代码有什么问题。有时候真的是一件小事,你连调试都花这么长的时间才看到错误!再次感谢。投票,奖励赏金并设置为答案;)
  • 是的,我不太喜欢这样直接翻译成java的风格。 boolean->int 很不和谐,我不喜欢所有嵌套的 if。
  • 无论如何,我很高兴它有帮助。
  • 是的,我也不是,有时真的很混乱!嵌套的 if 让它看起来比实际更难,虽然更短!