classRBTreeNode<T extendsComparable<T>> { private T value;//node value private RBTreeNode<T> left;//left child pointer private RBTreeNode<T> right;//right child pointer private RBTreeNode<T> parent;//parent pointer privateboolean red;//color is red or not red }
/** * add node * @param node * @return */ public T addNode(RBTreeNode<T> node){ //init node node.setLeft(null); setParent(node,null); node.setRight(null); node.setRed(true);
//Determine whether the header node is empty if (root.getLeft() == null){ //node become root root.setLeft(node); //root is black node.makeBlack(); }else { //find insert point RBTreeNode<T> x = findParentNode(node); intcmp= x.getValue().compareTo(node.getValue());
/** * red black tree insert fix. * when Red is connected to red, we need fix RBTress。 * if insert node's uncle is null(black), * case 1: LL type, rotate right, change the color of parent and ancestor * case 2: RR type, rotate left, change the color of parent and ancestor * case 3: LR type, first rotate left and then rotate right, change the color of current and ancestor * case 4: RL type, first rotate Right and then rotate left, change the color of current and ancestor * else insert node's uncle is red: * change the color of parent、uncle with ancestor,and look on the ancestor as new insert node * @param node is new node */ privatevoidfixInsert(RBTreeNode<T> node) { RBTreeNode<T> parent = node.getParent();
//whether need to fix while (parent != null && parent.isRed()) { //get uncle RBTreeNode<T> uncle = getUncle(node);
if(uncle == null || uncle.isBlack()) { //uncle is black, have 4 cases RBTreeNode<T> ancestor = parent.getParent(); if (ancestor.getLeft() == parent){ booleanisRight= node == parent.getRight(); if (isRight) { rotateLeft(parent); } rotateRight(ancestor);
if (isRight) { //change the color of current and ancestor node.makeBlack();
ancestor.makeRed(); } }else{ //change the color of parent、uncle with ancestor parent.makeBlack(); uncle.makeBlack(); RBTreeNode<T> ancestor = parent.getParent(); ancestor.makeRed();
//ancestor as new insert node node = parent.getParent(); parent = node.getParent(); } }
//make sure root is black RBTreeNode<T> root = getRoot(); root.makeBlack(); setParent(root, null); }
/** * rotate right * @param node */ privatevoidrotateRight(RBTreeNode<T> node) { //get left RBTreeNode<T> left = node.getLeft(); if(left==null){ thrownewjava.lang.IllegalStateException("left node is null"); } //get parent RBTreeNode<T> parent = node.getParent();
//leftRight move to node's left RBTreeNode<T> leftRight = left.getRight(); node.setLeft(leftRight); setParent(leftRight, node);
//node move to leftRight left.setRight(node); setParent(node, left);