Search code examples
javared-black-tree

Inserted nodes in red-black tree get wrong colouring


I want to change the color of root Node to black when the color of root.right and root are red. Now In this code first i insert 5 so color of this root will be black.Then i inserted 6 then color of this node will be red then i inserted 7 then color of this node will be red.So now This node and the previous node have red color So here i need to change the color of previous Node which contains data=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
 }

}

Solution

  • You are setting the color to red here:

    root.right.color=Color.red;
    

    So this line has to print red instead of black:

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

    Note that even if you set the color of root.right to red inside of the inner call to insertion, when it returns to the outter insertion you do this:

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

    so, you are overwriting whatever color you had set root.right to be always red.