/** * invariant: curent node (c) is not a 2-node * * @param c * @return */ private Node fixUp(Node c) { if (isRed(c.right)) c = rotateLeft(c); if (isRed(c.left) && isRed(c.left.left)) c = rotateRight(c); // eliminate 4-nodes on the way up if (isRed(c.left) && isRed(c.right)) flipColor(c); return c; }
private Node insert(Node current, Key key, Value value) { // insert at the bottom if (current == null) { previousValue = null; size++; return new Node(key, value); } // split 4-nodes (both of left and right edges are red) on the way down if (isRed(current.left) && isRed(current.right)) flipColor(current); int cmp = key.compareTo(current.key); if (cmp == 0) { previousValue = current.value; current.value = value; // previous value is overwritten because no duplicate keys are allowed } else if (cmp < 0) current.left = insert(current.left, key, value); else current.right = insert(current.right, key, value); // enforce the left-leaning condition if (isRed(current.right)) current = rotateLeft(current); // balance 4-node (two reds in the left) if (isRed(current.left) && isRed(current.left.left)) current = rotateRight(current); return current; }