红黑树中插入的节点着色错误

Inserted nodes in red-black tree get wrong colouring

当root.right和root的颜色都是红色的时候,我想把root节点的颜色改成黑色。 现在在这段代码中,我首先插入 5,所以这个根的颜色将是 black.Then 我插入 6 然后这个节点的颜色将是红色然后我插入 7 然后这个节点的颜色现在将是 red.So 这个节点并且前一个节点有红色所以在这里我需要更改包含数据= 6

的前一个节点的颜色
package redblack;

public class Redblack {
public enum Color {
   red,black,blue
};
   static class Node{
      int data;
      Color color;
      Node right;
      Node parent;
      Node(int data){
          color=Color.black;
          this.data=data;
          right=null;
          parent =null;
      }
  }  
        static Node insertion(Node root,int data){
      if(root==null){
          Node root1=new Node(data);
          return root1;
      }
      if(root.data<data){
      root.right=insertion(root.right,data);
      root.right.parent=root;
      root.right.color=Color.red;
      if(root.parent!=null)
      root.color=Color.black; // Whats wrong here?
      }
      return root;
  }
        public static void main(String[] args) {
  Node root=new Node(5);
  root=insertion(root,6);
  root=insertion(root,7);
    System.out.println(root.right.color); //Getting red color but i want black color here
 }

}

您在这里将颜色设置为红色:

root.right.color=Color.red;

所以这一行必须打印红色而不是黑色:

System.out.println(root.right.color);

请注意,即使您在对 insertion 的内部调用中将 root.right 的颜色设置为红色,当它 returns 设置为外部 insertion 时,您也会这样做这个:

root.right=insertion(root.right,data);
...
root.right.color=Color.red;

因此,您正在覆盖您设置 root.right 始终为红色的任何颜色。

您没有为 root.parent 分配任何值,因此它始终为 null 并且在此代码中 root=insertion(root,7); 您正在删除之前的权利并重新插入红色的新权利应将此 root=insertion(root,7); 替换为 root.right=insertion(root.right,7);