<titledata-rh="true">On the rules of the red-black tree | mf</title><metadata-rh="true"name="viewport"content="width=device-width,initial-scale=1"><metadata-rh="true"name="twitter:card"content="summary_large_image"><metadata-rh="true"property="og:url"content="https://blog.mfocko.xyz/ib002/rb-trees/rules/"><metadata-rh="true"name="docusaurus_locale"content="en"><metadata-rh="true"name="docsearch:language"content="en"><metadata-rh="true"name="docusaurus_version"content="current"><metadata-rh="true"name="docusaurus_tag"content="docs-ib002-current"><metadata-rh="true"name="docsearch:version"content="current"><metadata-rh="true"name="docsearch:docusaurus_tag"content="docs-ib002-current"><metadata-rh="true"property="og:title"content="On the rules of the red-black tree | mf"><metadata-rh="true"name="description"content="Showerthoughtsontherulesofthered-blacktree.
formulated the way they are? How come they keep the tree balanced? Let's go through
each of the red-black tree rules and try to change, break and contemplate about
them.</p><p>We expect that you are familiar with the following set of the rules<supid="fnref-1"><ahref="#fn-1"class="footnote-ref">1</a></sup>:</p><ol><li>Every node is either red or black.</li><li>The root is black.</li><li>Every leaf (<code>nil</code>) is black.</li><li>If a node is red, then both its children are black.</li><li>For each node, all simple paths from the node to descendant leaves contain the
same number of black nodes.</li></ol><p>Each section will go into <em>reasonable</em> details of each rule.</p><h2class="anchor anchorWithStickyNavbar_LWe7"id="1ª-every-node-is-either-red-or-black">1ª Every node is either red or black.<ahref="#1ª-every-node-is-either-red-or-black"class="hash-link"aria-label="Direct link to 1ª Every node is either red or black."title="Direct link to 1ª Every node is either red or black."></a></h2><p>OK… This one is very simple. It is just a definition and is used in all other
rules. Not much to talk about here. Or is there?</p><h3class="anchor anchorWithStickyNavbar_LWe7"id="do-i-really-need-the-nodes-to-be-explicitly-colored">Do I really need the nodes to be explicitly colored?<ahref="#do-i-really-need-the-nodes-to-be-explicitly-colored"class="hash-link"aria-label="Direct link to Do I really need the nodes to be explicitly colored?"title="Direct link to Do I really need the nodes to be explicitly colored?"></a></h3><p>The answer is no. Balancing of the red-black trees is “enforced” by the 4th and
5th rule in the enumeration above. There are many ways you can avoid using colors.</p><h4class="anchor anchorWithStickyNavbar_LWe7"id="black-height">Black height<ahref="#black-height"class="hash-link"aria-label="Direct link to Black height"title="Direct link to Black height"></a></h4><p>We mentioned the 4th and 5th rule and that it enforces the balancing. What does
it mean for us?</p><p>Well, we definitely do not have to use the colors, which even as a <em>boolean</em> flag
would take at least 1 byte of space (and usually even more), cause… well, it is
easier for the CPU to work with words rather than single bits.</p><p>We could use the black height, couldn't we? It would mean more memory used, cause
it should be ideally big and unsigned. Can we tell the color of a node from the
black height? Of course we can, if my child has the same black height as I do,
it means that there was no black node added on the path between us and therefore
my child would be colored red.</p><p>Example of a red-black tree that keeps count of black nodes on paths to the
leaves follows:</p><p><imgloading="lazy"alt="Red-black tree with black height"src="/assets/images/rb_height_light-0aff6e7a40a9f601e0dd1114e43e43b1.svg#gh-light-mode-only"width="923"height="539"class="img_ev3q">
<imgloading="lazy"alt="Red-black tree with black height"src="/assets/images/rb_height_dark-921b2d98d9fe1e579474faf36486f281.svg#gh-dark-mode-only"width="923"height="539"class="img_ev3q"></p><p>We mark the <em>black heights</em> in superscript. You can see that all leaves have the
black height equal to <spanclass="math math-inline"><spanclass="katex"><spanclass="katex-mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>1</mn></mrow><annotationencoding="application/x-tex">1</annotation></semantics></math></span><spanclass="katex-html"aria-hidden="true"><spanclass="base"><spanclass="strut"style="height:0.6444em"></span><spanclass="mord">1</span></span></span></span></span>. Let's take a look at some of the interesting cases:</p><ul><li><p>If we take a look at the node with <spanclass="math math-inline"><spanclass="katex"><spanclass="katex-mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mtext>key</mtext><mo>=</mo><mn>9</mn></mrow><annotationencoding="application/x-tex">\text{key} = 9</annotation></semantics></math></span><spanclass="katex-html"aria-hidden="true"><spanclass="base"><spanclass="strut"style="height:0.8889em;vertical-align:-0.1944em"></span><spanclass="mord text"><spanclass="mord">key</span></span><spanclass="mspace"style="margin-right:0.2778em"></span><spanclass="mrel">=</span><spanclass="mspace"style="margin-right:0.2778em"></span></span><spanclass="base"><spanclass="strut"style="height:0.6444em"></span><spanclass="mord">9</span></span></span></span></span>, we can see that it is
coloured red and its black height is 1, because it is a leaf.</p><p>Let's look at its parent (node with <spanclass="math math-inline"><spanclass="katex"><spanclass="katex-mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mtext>key</mtext><mo>=</mo><mn>8</mn></mrow><annotationencoding="application/x-tex">\text{key} = 8</annotation></semantics></math></span><spanclass="katex-html"aria-hidden="true"><spanclass="base"><spanclass="strut"style="height:0.8889em;vertical-align:-0.1944em"></span><spanclass="mord text"><spanclass="mord">key</span></span><spanclass="mspace"style="margin-right:0.2778em"></span><spanclass="mrel">=</span><spanclass="mspace"style="margin-right:0.2778em"></span></span><spanclass="base"><spanclass="strut"style="height:0.6444em"></span><spanclass="mord">8</span></span></span></span></span>). On its left side it has
<code>nil</code> and on its right side the <spanclass="math math-inline"><spanclass="katex"><spanclass="katex-mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>9</mn></mrow><annotationencoding="application/x-tex">9</annotation></semantics></math></span><spanclass="katex-html"aria-hidden="true"><spanclass="base"><spanclass="strut"style="height:0.6444em"></span><spanclass="mord">9</span></span></span></span></span>. And its black height is still <spanclass="math math-inline"><spanclass="katex"><spanclass="katex-mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>1</mn></mrow><annotationencoding="application/x-tex">1</annotation></semantics></math></span><spanclass="katex-html"aria-hidden="true"><spanclass="base"><spanclass="strut"style="height:0.6444em"></span><spanclass="mord">1</span></span></span></span></span>, cause
except for the <code>nil</code> leaves, there are no other black nodes.</p><p>We can clearly see that if a node has the same black height as its parent, it
is a red node.</p></li><li><p>Now let's take a look at the root with <spanclass="math math-inline"><spanclass="katex"><spanclass="katex-mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mtext>key</mtext><mo>=</mo><mn>3</mn></mrow><annotationencoding="application/x-tex">\text{key} = 3</annotation></semantics></math></span><spanclass="katex-html"aria-hidden="true"><spanclass="base"><spanclass="strut"style="height:0.8889em;vertical-align:-0.1944em"></span><spanclass="mord text"><spanclass="mord">key</span></span><spanclass="mspace"style="margin-right:0.2778em"></span><spanclass="mrel">=</span><spanclass="mspace"style="margin-right:0.2778em"></span></span><spanclass="base"><spanclass="strut"style="height:0.6444em"></span><spanclass="mord">3</span></span></span></span></span>. It has a black height
of 3. Both of its children are black nodes and have black height of 2.</p><p>We can see that if a node has its height 1 lower than its parent, it is a black
node.</p><p>The reasoning behind it is rather simple, we count the black nodes all the way
to the leaves, therefore if my parent has a higher black height, it means that
on the path from me to my parent there is a black node, but the only node added
is me, therefore I must be black.</p></li></ul><h4class="anchor anchorWithStickyNavbar_LWe7"id="isomorphic-trees">Isomorphic trees<ahref="#isomorphic-trees"class="hash-link"aria-label="Direct link to Isomorphic trees"title="Direct link to Isomorphic trees"></a></h4><p>One of the other ways to avoid using color is storing the red-black tree in some
isomorphic tree. The structure of 2-3-4 tree allows us to avoid using the color
completely. This is a bit different approach, cause we would be basically using
different tree, so we keep this note in just as a “hack”.</p><h2class="anchor anchorWithStickyNavbar_LWe7"id="2ª-the-root-is-black">2ª The root is black.<ahref="#2ª-the-root-is-black"class="hash-link"aria-label="Direct link to 2ª The root is black."title="Direct link to 2ª The root is black."></a></h2><p>This rule might seem like a very important one, but overall is not. You can safely
omit this rule, but you also need to deal with the consequences.</p><p>Let's refresh our memory with the algorithm of <em>insert fixup</em>:</p><divclass="codeBlockContainer_Ckt0 theme-code-block"style="--prism-color:#000000;--prism-background-color:#ffffff"><divclass="codeBlockContent_biex"><pretabindex="0"class="prism-code language-text codeBlock_bY9V thin-scrollbar"><codeclass="codeBlockLines_e6Vv"><spanclass="token-line"style="color:#000000"><spanclass="token plain">WHILE z.p.color == Red</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> IF z.p == z.p.p.left</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> y = z.p.p.right</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"style="display:inline-block"></span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> IF y.color == Red</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> z.p.color = Black</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> y.color = Black</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> z.p.p.color = Red</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> z = z.p.p</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> ELSE</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> IF z == z.p.right</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> z = z.p</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> Left-Rotate(T, z)</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> z.p.color = Black</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> z.p.p.color = Red</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> Right-Rotate(T, z.p.p)</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"> ELSE (same as above with “right” and “left” exchanged)</span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain"style="display:inline-block"></span><br></span><spanclass="token-line"style="color:#000000"><spanclass="token plain">T.root.color = Black</span><br></span></code></pre><divclass="buttonGroup__atx"><buttontype="button"aria-label="Copy code to clipboard"title="Copy"class="clean-btn"><spanclass="copyButtonIcons_eSgA"aria-hidden="true"><svgviewBox="0 0 24 24"class="copyButtonIcon_y97N"><pathfill="currentColor"d="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z"></path></svg><svgviewBox="0 0 24 24"class="copyButtonSuccessIcon_LjdS"><pathfill="currentColor"d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z"></path></svg></span></button></div></div></div><divclass="theme-admonition theme-admonition-tip alert alert--success admonition_LlT9"><divclass="admonitionHeading_tbUL"><spanclass="admonitionIcon_kALy"><svgviewBox="0 0 12 16"><pathfill-rule="evenodd"d="M6.5 0C3.48 0 1 2.19 1 5c0 .92.55 2.25 1 3 1.34 2.25 1.78 2.78 2 4v1h5v-1c.22-1.22.66-1.75 2-4 .45-.75 1-2.08 1-3 0-2.81-2.48-5-5.5-5zm3.64 7.48c-.25.44-.47.8-.67 1.11-.86 1.41-1.25 2.06-1.45 3.23-.02.05-.02.11-.02.17H5c0-.06 0-.13-.02-.17-.2-1.17-.59-1.83-1.45-3.23-.2-.31-.42-.67-.67-1.11C2.44 6.78 2 5.65 2 5c0-2.2 2.02-4 4.5-4 1.22 0 2.36.42 3.22 1.19C10.55 2.94 11 3.94 11 5c0 .66-.44 1.78-.86 2.48zM4 14h5c-.23 1.14-1.3 2-2.5 2s-2.27-.86-2.5-2z"></path></svg></span>tip</div><divclass="admonitionContent_S0QG"><p>If you have tried to implement any of the more complex data structures, such as
red-black trees, etc., in a statically typed language that also checks you for
<code>NULL</code>-correctness (e.g. <em>mypy</em> or even C# with nullable reference types), you
might have run into numerous issues in the cases where you are 100% sure that you
cannot obtain <code>NULL</code> because of the invariants, but the static type checking
doesn't know that.</p><p>The issue we hit with the <em>insert fixup</em> is very similar.</p></div></div><p>You might not realize the issue at the first sight, but the algorithm described
with the pseudocode above expects that the root of the red-black tree is black by
both relying on the invariant in the algorithm and afterwards by enforcing the
black root property.</p><p>If we decide to omit this condition, we need to address it in the pseudocodes
accordingly.</p><table><thead><tr><thalign="center">Usual algorithm with black root</th><thalign="center">Allowing red root</th></tr></thead><tbody><tr><tdalign="center"><imgloading="lazy"alt="1ª insertion"src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZ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giIHRyYW5zZm9ybT0ic2NhbGUoMSAxKSByb3RhdGUoMCkgdHJhbnNsYXRlKDQgMTEyKSI+Cjx0aXRsZT5SQlRyZWU8L3RpdGxlPgo8cG9seWdvbiBmaWxsPSIjMWIxYjFkIiBzdHJva2U9InRyYW5zcGFyZW50IiBwb2ludHM9Ii00LDQgLTQsLTExMiAxMzAsLTExMiAxMzAsNCAtNCw0Ii8+CjwhLS0gMTQwMzk5ODA1NjAzMjgwIC0tPgo8ZyBpZD0ibm9kZTEiIGNsYXNzPSJub2RlIj4KPHRpdGxlPjE0MDM5OTgwNTYwMzI4MDwvdGl0bGU+CjxlbGxpcHNlIGZpbGw9Im5vbmUiIHN0cm9rZT0id2hpdGUiIGN4PSI2MyIgY3k9Ii05MCIgcng9IjI3IiByeT0iMTgiLz4KPHRleHQgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iNjMiIHk9Ii04Ni4zIiBmb250LWZhbWlseT0iJ0Nhc2NhZGlhIENvZGUgUEwnLCAnSmV0QnJhaW5zIE1vbm8nLCAnSW9zZXZrYScsICdGaXJhIENvZGUnLCAnSGFjaycsIG1vbm9zcGFjZSIgZm9udC1zaXplP
<imgloading="lazy"src="/assets/images/rb_dark-2917b0f8de62597646b619102f126a53.svg#gh-dark-mode-only"width="899"height="539"class="img_ev3q"></p><p>We should start by counting the black nodes from root to the <code>nil</code> leaves based
on the rules. We have multiple similar paths, so we will pick only the interesting
ones.</p><ol><li>What happens if we do not count the <code>nil</code> leaves?</li><li>What happens if we consider leaves the nodes with <em>no descendants</em>, i.e. both
of node's children are <code>nil</code>?</li><li>What happens if we do not count the <code>nil</code> leaves, but consider nodes with at
least one <code>nil</code> descendant as leaves?</li></ol><table><thead><tr><thalign="right">path</th><thalign="right">black nodes</th><thalign="right">1ª idea</th><thalign="right">2ª idea</th><thalign="right">3ª idea</th></tr></thead><tbody><tr><tdalign="right"><code>3 → 1 → 0 → nil</code></td><tdalign="right">4</td><tdalign="right">3</td><tdalign="right">4</td><tdalign="right">3</td></tr><tr><tdalign="right"><code>3 → 5 → 7 → 8 → nil</code></td><tdalign="right">4</td><tdalign="right">3</td><tdalign="right">-</td><tdalign="right">3</td></tr><tr><tdalign="right"><code>3 → 5 → 7 → 8 → 9 → nil</code></td><tdalign="right">4</td><tdalign="right">3</td><tdalign="right">4</td><tdalign="right">3</td></tr></tbody></table><p>First idea is very easy to execute and it is also very easy to argue about its
correctness. It is correct, because we just subtract one from each of the paths.
This affects <strong>all</strong> paths and therefore results in global decrease by one.</p><p>Second idea is a bit more complicated. We count the <code>nil</code>s, so the count is <spanclass="math math-inline"><spanclass="katex"><spanclass="katex-mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>4</mn></mrow><annotationencoding="application/x-tex">4</annotation></semantics></math></span><spanclass="katex-html"aria-hidden="true"><spanclass="base"><spanclass="strut"style="height:0.6444em"></span><spanclass="mord">4</span></span></span></span></span>
as it should be. However, there is one difference. Second path no longer satisfies
the condition of a <em>leaf</em>. Technically it relaxes the 5th rule, because we leave
out some of the nodes. We should probably avoid that.</p><divclass="theme-admonition theme-admonition-caution alert alert--warning admonition_LlT9"><divclass="admonitionHeading_tbUL"><spanclass="admonitionIcon_kALy"><svgviewBox="0 0 16 16"><pathfill-rule="evenodd"d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 0 0 0 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 0 0 .01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"></path></svg></span>caution</div><divclass="admonitionContent_S0QG"><p>With the second idea, you may also feel that we are “bending” the rules a bit,
especially the definition of the “leaf” nodes.</p><p>Given the definition of the red-black tree, where <code>nil</code> is considered to be an
external node, we have decided that bending it a bit just to stir a thought about
it won't hurt anybody. 😉</p></div></div><h2class="anchor anchorWithStickyNavbar_LWe7"id="4ª-if-a-node-is-red-then-both-its-children-are-black">4ª If a node is red, then both its children are black.<ahref="#4ª-if-a-node-is-red-then-both-its-children-are-black"class="hash-link"aria-label="Direct link to 4ª If a node is red, then both its children are black."title="Direct link to 4ª If a node is red, then both its children are black."></a></h2><p>This rule might seem rather silly on the first look, but there are 2 important
functions:</p><ol><li>it allows the algorithms to <em>“notice”</em> that something went wrong (i.e. the
tree needs to be rebalanced), and</li><li>it holds the balancing and height of the tree <em>“in check”</em> (with the help of
the 5th rule).</li></ol><p>When we have a look at the algorithms that are used for fixing up the red-black
tree after an insertion or deletion, we will notice that all the algorithms need
is the color of the node. </p><blockquote><p>How come it is the only thing that we need?
How come such naïve thing can be enough?</p></blockquote><p>Let's say we perform an insertion into the tree… We go with the usual and pretty
primitive insertion into the binary-search tree and then, if needed, we “fix up”
broken invariants. <em>How can that be enough?</em> With each insertion and deletion we
maintain the invariants, therefore if we break them with one operation, there's
only one path on which the invariants were <em>felled</em>. If we know that rest of the
tree is correct, it allows us to fix the issues just by propagating it to the
root and <em>abusing</em> the siblings (which are, of course, correct red-black
subtrees) to fix or at least partially mitigate the issues and propagate them
further.</p><p>Let's assume that we do not enforce this rule, you can see how it breaks the
balancing of the tree below.</p><divclass="tabs-container tabList__CuJ"><ulrole="tablist"aria-orientation="horizontal"class="tabs"><lirole="tab"tabindex="0"aria-selected="true"class="tabs__item tabItem_LNqP tabs__item--active">Enforcing this rule</li><lirole="tab"tabindex="-1"aria-selected="false"class="tabs__item tabItem_LNqP">Omitting this rule</li></ul><divclass="margin-top--md"><divrole="tabpanel"class="tabItem_Ymn6"><p><imgloading="lazy"src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIKICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdm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tYW5jaG9yPSJtaWRkbGUiIHg9Ijk5IiB5PSItODYuMyIgZm9udC1mYW1pbHk9IidDYXNjYWRpYSBDb2RlIFBMJywgJ0pldEJyYWlucyBNb25vJywgJ0lvc2V2a2EnLCAnRmlyYSBDb2RlJywgJ0hhY2snLCBtb25vc3BhY2UiIGZvbnQtc2l6ZT0iMTQuMDAiPjA8L3RleHQ+CjwvZz4KPCEtLSBOb2RlKHZhbHVlPTEsIHJhbms9MSkmIzQ1OyZndDtOb2RlK
<imgloading="lazy"src="/assets/images/incorrect_dark-d9c04aed74f7d364c3c3b1855b769ab0.svg#gh-dark-mode-only"width="803"height="443"class="img_ev3q"></p></div></div></div><p>We can create a <strong>big</strong> subtree with only red nodes and <strong>even</strong> when keeping
the rest of the rules maintained, it will break the time complexity. It stops us
from “hacking” the black height requirement laid by the 5th rule.</p><h2class="anchor anchorWithStickyNavbar_LWe7"id="5ª-for-each-node-all-simple-paths-from-the-node-to-descendant-leaves-contain-the-same-number-of-black-nodes">5ª For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.<ahref="#5ª-for-each-node-all-simple-paths-from-the-node-to-descendant-leaves-contain-the-same-number-of-black-nodes"class="hash-link"aria-label="Direct link to 5ª For each node, all simple paths from the node to descendant leaves contain the same number of black nodes."title="Direct link to 5ª For each node, all simple paths from the node to descendant leaves contain the same number of black nodes."></a></h2><p>As it was mentioned, with the 4th rule they hold the balancing of the red-black
tree.</p><divclass="theme-admonition theme-admonition-tip alert alert--success admonition_LlT9"><divclass="admonitionHeading_tbUL"><spanclass="admonitionIcon_kALy"><svgviewBox="0 0 12 16"><pathfill-rule="evenodd"d="M6.5 0C3.48 0 1 2.19 1 5c0 .92.55 2.25 1 3 1.34 2.25 1.78 2.78 2 4v1h5v-1c.22-1.22.66-1.75 2-4 .45-.75 1-2.08 1-3 0-2.81-2.48-5-5.5-5zm3.64 7.48c-.25.44-.47.8-.67 1.11-.86 1.41-1.25 2.06-1.45 3.23-.02.05-.02.11-.02.17H5c0-.06 0-.13-.02-.17-.2-1.17-.59-1.83-1.45-3.23-.2-.31-.42-.67-.67-1.11C2.44 6.78 2 5.65 2 5c0-2.2 2.02-4 4.5-4 1.22 0 2.36.42 3.22 1.19C10.55 2.94 11 3.94 11 5c0 .66-.44 1.78-.86 2.48zM4 14h5c-.23 1.14-1.3 2-2.5 2s-2.27-.86-2.5-2z"></path></svg></span>tip</div><divclass="admonitionContent_S0QG"><p>An important observation here is the fact that the red-black tree is a
<strong>height</strong>-balanced tree.</p></div></div><p>Enforcing this rule (together with the 4th rule) keeps the tree balanced:</p><ol><li>4th rule makes sure we can't “hack” this requirement.</li><li>This rule ensures that we have “similar”<supid="fnref-2"><ahref="#fn-2"class="footnote-ref">2</a></sup> length to each of the leaves.</li></ol><divclass="theme-admonition theme-admonition-tip alert alert--success admonition_LlT9"><divclass="admonitionHeading_tbUL"><spanclass="admonitionIcon_kALy"><svgviewBox="0 0 12 16"><pathfill-rule="evenodd"d="M6.5 0C3.48 0 1 2.19 1 5c0 .92.55 2.25 1 3 1.34 2.25 1.78 2.78 2 4v1h5v-1c.22-1.22.66-1.75 2-4 .45-.75 1-2.08 1-3 0-2.81-2.48-5-5.5-5zm3.64 7.48c-.25.44-.47.8-.67 1.11-.86 1.41-1.25 2.06-1.45 3.23-.02.05-.02.11-.02.17H5c0-.06 0-.13-.02-.17-.2-1.17-.59-1.83-1.45-3.23-.2-.31-.42-.67-.67-1.11C2.44 6.78 2 5.65 2 5c0-2.2 2.02-4 4.5-4 1.22 0 2.36.42 3.22 1.19C10.55 2.94 11 3.94 11 5c0 .66-.44 1.78-.86 2.48zM4 14h5c-.23 1.14-1.3 2-2.5 2s-2.27-.86-2.5-2z"></path></svg></span>AVL tree</div><divclass="admonitionContent_S0QG"><p>You might have heard about an <em>AVL tree</em> before. It is the first self-balanced
tree to be ever introduced and works in a very similar nature as the red-black
tree, the only difference is that it does not deal with the <em>black height</em>, but
the height in general.</p><p>If you were to compare AVL with the red-black tree, you can say that AVL is much
more strict while red-black tree can still maintain the same asymptotic time
complexity for the operations, but having more relaxed rules.</p></div></div><divclass="footnotes"><hr><ol><liid="fn-1">CORMEN, Thomas. Introduction to algorithms. Cambridge, Mass: MIT Press, 2009. isbn 9780262033848.<ahref="#fnref-1"class="footnote-backref">↩</a></li><liid="fn-2">red nodes still exist<ahref="#fnref-2"class="footnote-backref">↩</a></li></ol></div></div><footerclass="theme-doc-footer docusaurus-mt-lg"><divclass="theme-doc-footer-tags-row row margin-bottom--sm"><divclass="col"><b>Tags:</b><ulclass="tags_jXut padding--none margin-left--sm"><liclass="tag_QGVx"><aclass="tag_zVej tagRegular_sFm0"href="/ib002/tags/red-black-trees/">red-black trees</a></li><liclass="tag_QGVx"><aclass="tag_zVej tagRegular_sFm0"href="/ib002/tags/balanced-trees/">balanced trees</a></li></ul></div></div><divclass="theme-doc-footer-edit-meta-row row"><divclass="col"><ahref="https://gitlab.com/mfocko/blog/tree/main/ib002/08-rb-trees/2023-06-10-rules.md"target="_blank"rel="noreferrer noopener"class="theme-edit-this-page"><svgfill="currentColor"height="20"width="20"viewBox="0 0 40 40"class="iconEdit_Z9Sw"aria-hidden="true"><g><pathd="m34.5 11.7l-3 3.1-6.3-6.3 3.1-3q0.5-0.5 1.2-0.5t1.1 0.5l3.9 3.9q0.5 0.4 0.5 1.1t-0.5 1.2z m-29.5 17.1l18.4-18.5 6.3 6.3-18.4 18.4h-6.3v-6.2z"></path></g></svg>Edit this page</a></div><divclass="col lastUpdated_vwxv"><spanclass="theme-last-updated">Last updated<!----> on <b><timedatetime="2023-06-10T00:00:00.000Z">Jun 10, 2023</time></b></span></div></div></footer></article><navclass="pagination-nav docusaurus-mt-lg"aria-label="Docs pages"><aclass="pagination-nav__link pagination-nav__link--prev"href="/ib002/rb-trees/applications/"><divclass="pagination-nav__sublabel">Previous</div><divclass="pagination-nav__label">Použití červeno-černých stromů</div></a><aclass="pagination-nav__link pagination-nav__link--next"href="/ib002/category/graphs/"><divclass="pagination-nav__sublabel">Next</div><divclass="pagination-nav__label">Graphs</div></a></nav></div></div><divclass="col col--3"><divclass="tableOfContents_bqdL thin-scrollbar theme-doc-toc-desktop"><ulclass="table-of-contents table-of-contents__left-border"><li><ahref="#introduction"class="table-of-contents__link toc-highlight">Introduction</a></li><li><ahref="#1ª-every-node-is-either-red-or-black"class="table-of-contents__link toc-highlight">1ª Every node is either red or black.</a><ul><li><ahref="#do-i-really-need-the-nodes-to-be-explicitly-colored"class="table-of-contents__link toc-highlight">Do I really need the nodes to be explicitly colored?</a></li></ul></li><li><ahref="#2ª-the-root-is-black"class="table-of-contents__link toc-highlight">2ª The root is black.</a></li><li><ahref="#3ª-every-leaf-nil-is-black"class="table-of-contents__link toc-highlight">3ª Every leaf (<code>nil</code>) is black.</a></li><li><ahref="#4ª-if-a-node-is-red-then-both-its-children-are-black"class="table-of-contents__link toc-highlight">4ª If a node is red, then both its children are black.</a></li><li><ahref="#5ª-for-each-node-all-simple-paths-from-the-node-to-descendant-leaves-contain-the-same-number-of-black-nodes"class="table-of-contents__link toc-highlight">5ª For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.</a></li></ul></div></div></div></div></main></div></div><footerclass="footer footer--dark"><divclass="container container-fluid"><divclass="row footer__links"><divclass="col footer__col"><divclass="footer__title">Git</div><ulclass="footer__items clean-list"><liclass="footer__item"><ahref="https://github.com/mfocko"target="_blank"rel="noopener noreferrer"class="footer__link-item">GitHub<svgwidth="13.5"height="13.5"aria-hidden="true"viewBox="0 0 24 24"class="iconExternalLink_nPIU"><pathfill="currentColor"d="M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"></path></svg></a></li><liclass="footer__item"><ahref="https://gitlab.com/mfocko"target="_blank"rel="