{"id":123,"date":"2026-11-13T12:32:00","date_gmt":"2026-11-13T04:32:00","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-red-black-tree-fixes-insert-with-colors\/"},"modified":"2026-11-13T21:50:49","modified_gmt":"2026-11-13T13:50:49","slug":"how-a-red-black-tree-fixes-insert-with-colors","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-red-black-tree-fixes-insert-with-colors\/","title":{"rendered":"How a red-black tree fixes insert with colors"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> A <strong>red-black tree<\/strong> is a binary search tree with red and black nodes. The root is black, every red node has two black children, and every path from a node to a leaf sentinel carries the same number of black nodes. Those rules keep the height at most <strong>2 log\u2082(n+1)<\/strong>. Insert colors the new node red and repairs with recoloring and at most two rotations. Delete is the longer case. Search, insert, and delete are <strong>O(log n)<\/strong> worst case.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">AVL stores a height and rotates to keep factors tiny. A red-black tree stores one bit and keeps a weaker invariant that is still strong enough for a logarithmic height. The black-height rule says no path is more than twice another, because a red node must be followed by a black one, so at most half the nodes on a path are red.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Insert puts a red node at a leaf so the black-height does not change. The only violation is a red child of a red parent. The uncle&#8217;s color decides the repair. A red uncle recolors and moves the problem toward the root. A black uncle rotates.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">All dictionary operations are O(log n) worst case. Extra memory is one color bit and the child pointers, usually with a black sentinel instead of null so the leaf rule is uniform. The in-order sequence is the sorted order. Standard-library ordered maps are often red-black trees, because the insert fixup is a short loop and the constant factors compete well with AVL.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Delete removes a node and can leave a double-black hole. The fixup pushes that hole toward the root by rotations and recolors that depend on the sibling. It is the part to implement from a case table, not from memory of the insert loop. A tree that only implements insert and search still needs the insert uncle cases, or a sorted insert paints a red path and the height bound is gone.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Search for the key. On a miss, create a red node in that leaf position. A duplicate is an update of the existing node, not a second insert.<\/li>\n<li>While the parent is red, inspect the uncle. If the uncle is red, color the parent and the uncle black, color the grandparent red, and continue from the grandparent.<\/li>\n<li>If the uncle is black and the node is an inner child, rotate the parent so the node becomes an outer child. Then color the parent black, the grandparent red, and rotate the grandparent.<\/li>\n<li>Color the root black at the end. The black-height rule is restored.<\/li>\n<li>For delete, if the removed color was black, run the double-black fixup from the hole, using the sibling&#8217;s color and the sibling&#8217;s children, until the hole is a red node that can be painted black or the root is reached.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The 2 log(n+1) height is looser than AVL&#8217;s and still logarithmic. A red-black tree is not a B-tree, and painting nodes red and black without the uncle test does not keep the black-height. Hash tables are the alternative when order and predecessor queries are not required.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when a red node is given a red child and left there<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Insert red and skip the uncle test<\/td>\n<td>A sorted sequence becomes a red chain. Paths no longer share a black-height, and the tree is a linked list.<\/td>\n<\/tr>\n<tr>\n<td>Rotate without recoloring<\/td>\n<td>The shape may look balanced while two reds remain adjacent or a black-height changes on only one side.<\/td>\n<\/tr>\n<tr>\n<td>Treat delete as the insert cases run backward<\/td>\n<td>Delete introduces a missing black, not a extra red. The sibling cases are a different table.<\/td>\n<\/tr>\n<tr>\n<td>Use a null leaf as red<\/td>\n<td>The leaf rule counts black nodes down to a sentinel. A missing sentinel convention changes every case. Pick black sentinels and keep them.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Stricter height balance is the AVL tree. A randomized balance with the same expected depth is a treap. An ordered map that must stay logarithmic on adversarial keys is this tree or AVL, not a hash table.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment fixes a red-black insertion by the uncle test. A red node has black children, and every path carries the same number of black nodes. Inserting 1, 2, 3 leaves a black root. It prints the inorder keys and colors, <code>1R 2B 3R<\/code>.<\/p>\n\n<pre><code class=\"language-python\">RED, BLACK = &quot;R&quot;, &quot;B&quot;\n\nclass N:\n    def __init__(self, key, color=RED):\n        self.key, self.color = key, color\n        self.left = self.right = self.parent = None\n\ndef rot_left(root, x):\n    y = x.right\n    x.right = y.left\n    if y.left:\n        y.left.parent = x\n    y.parent = x.parent\n    if x.parent is None:\n        root = y\n    elif x is x.parent.left:\n        x.parent.left = y\n    else:\n        x.parent.right = y\n    y.left = x\n    x.parent = y\n    return root\n\ndef rot_right(root, y):\n    x = y.left\n    y.left = x.right\n    if x.right:\n        x.right.parent = y\n    x.parent = y.parent\n    if y.parent is None:\n        root = x\n    elif y is y.parent.right:\n        y.parent.right = x\n    else:\n        y.parent.left = x\n    x.right = y\n    y.parent = x\n    return root\n\ndef insert(root, key):\n    node = N(key)\n    parent = None\n    cur = root\n    while cur:\n        parent = cur\n        cur = cur.left if key &lt; cur.key else cur.right\n    node.parent = parent\n    if parent is None:\n        root = node\n    elif key &lt; parent.key:\n        parent.left = node\n    else:\n        parent.right = node\n    while node.parent and node.parent.color == RED:\n        gp = node.parent.parent\n        if node.parent is gp.left:\n            uncle = gp.right\n            if uncle and uncle.color == RED:\n                node.parent.color = uncle.color = BLACK\n                gp.color = RED\n                node = gp\n            else:\n                if node is node.parent.right:\n                    node = node.parent\n                    root = rot_left(root, node)\n                node.parent.color = BLACK\n                gp.color = RED\n                root = rot_right(root, gp)\n        else:\n            uncle = gp.left\n            if uncle and uncle.color == RED:\n                node.parent.color = uncle.color = BLACK\n                gp.color = RED\n                node = gp\n            else:\n                if node is node.parent.left:\n                    node = node.parent\n                    root = rot_right(root, node)\n                node.parent.color = BLACK\n                gp.color = RED\n                root = rot_left(root, gp)\n    root.color = BLACK\n    return root\n\ndef walk(n, out):\n    if n:\n        walk(n.left, out)\n        out.append(f&quot;{n.key}{n.color}&quot;)\n        walk(n.right, out)\n\nroot = None\nfor key in (1, 2, 3):\n    root = insert(root, key)\nout = []\nwalk(root, out)\nassert out == [&quot;1R&quot;, &quot;2B&quot;, &quot;3R&quot;]\nprint(*out)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The <strong>Linux CFS scheduler<\/strong> orders runnable tasks in a red-black tree keyed by virtual runtime. C++ <code>std::map<\/code> and Java <code>TreeMap<\/code> are red-black trees as well. The color fixes keep the height logarithmic after an insert. An AVL tree rotates more often for a stricter height.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop a from-scratch red-black tree when the language library already ships an ordered map. The delete fixup is easy to get wrong. Keep the structure when you are implementing that library, or when the color invariant itself is the object being discussed.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for a red-black tree returns the black-height rule and the uncle test that repairs a red insert. <strong>A red-black tree keeps search, insert, and delete at O(log n) by enforcing equal black-heights and repairing a red-red insertion with recoloring or at most two rotations.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: A red-black tree is a binary search tree with red and black nodes. The root is black, every red node has two black children, and every path from a node to a leaf sentinel carries the same number of black nodes. Those rules keep the height at&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,34],"tags":[],"class_list":["post-123","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-trees"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/123","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=123"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/123\/revisions"}],"predecessor-version":[{"id":522,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/123\/revisions\/522"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=123"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=123"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=123"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}