private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else if (cmp == 0) h.val = val; if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); return h; } 注解:最坏情况下各种操作的时间复杂度依然可以保持在O(lgN) Exercise: 1.In the extreme case, the red-black BST has only blacks links. A red-black BST of height h with no red links has 1 + 2 + 4 + ... + 2^h = 2^(h+1) - 1 nodes 2. 插入元素,树的高度反而有可能会降低 Consider inserting N keys in descending order into an initially empty red-black BST. Then, after each insertion, the height of the tree either strictly increases or remains unchanged. //In general, there is no reason to except the height to be monotonically nondecreasing. As a counterexample, after inserting the keys 7, 6, 5, 4, 3 and 2 into an initially empty red-black BST, the height is 3; after inserting the key 1, the height decreases to 2.