{"id":134,"date":"2026-11-13T12:32:20","date_gmt":"2026-11-13T04:32:20","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-an-avl-tree-restores-height-balance\/"},"modified":"2026-11-13T21:51:01","modified_gmt":"2026-11-13T13:51:01","slug":"how-an-avl-tree-restores-height-balance","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-an-avl-tree-restores-height-balance\/","title":{"rendered":"How an AVL tree restores height balance"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> An <strong>AVL tree<\/strong> is a binary search tree whose <strong>balance factor<\/strong>, left height minus right height, stays in <strong>\u22121, 0, +1<\/strong> at every node. An insertion or deletion that pushes a factor to \u00b12 is repaired by a single or a double rotation. The height is at most about <strong>1.44 log\u2082 n<\/strong>, so search, insert, and delete are <strong>O(log n)<\/strong> in the worst case. The tree is the strict height-balanced binary search tree.<\/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\">A binary search tree is O(n) when keys arrive sorted, because the tree becomes a path. An AVL tree forbids that shape. The balance factor is stored, or recomputed from heights, and a node with factor 2 or \u22122 has exactly one legal repair: a rotation toward the heavy side, preceded by a rotation of the child when the heavy side is itself bent the other way.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Those four pictures are LL, LR, RR, and RL. LL and RR are one rotation. LR and RL are two. After the rotation the subtree height is what it was before the insertion that caused the trouble, so a further ancestor does not also need repair on the way up from an insertion. Deletion is different: the height can drop, and the walk toward the root may rotate at several nodes.<\/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\">Search, insert, and delete are O(log n) worst case. The balance factors stay in range, and the height bound follows from the Fibonacci recurrence that describes the smallest AVL tree of a given height. Extra memory is a height or a balance factor per node, plus the pointers. In-order traversal is the sorted order, as in any binary search tree.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Rotations preserve the search-tree order. The middle node of the three nodes involved becomes the new subtree root, and the left and right subtrees are reattached so every key on the left stays smaller. A rotation that moves the wrong child breaks the order even if the heights look balanced. Red-black trees are a looser balance with a different color invariant and the same logarithmic bound. AVL is stricter and can perform more rotations on a heavy update mix.<\/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>Insert the key as in a binary search tree. Walk back toward the root, updating heights.<\/li>\n<li>At the first node whose balance factor is +2 or \u22122, look at the child&#8217;s factor to choose LL, LR, RR, or RL.<\/li>\n<li>LL means the left child is heavy on its left: rotate the node right. RR is the mirror. LR is a left rotation of the left child, then a right rotation of the node. RL is the mirror.<\/li>\n<li>After an insertion repair, stop. The subtree height is restored. After a deletion, continue up to the root, because a height drop can unbalance an ancestor.<\/li>\n<li>Search and in-order walk ignore the balance factors and use the search-tree links only.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The logarithmic bound needs the repair. A binary search tree with a height field and no rotations is still a path on sorted input. Red-black trees guarantee a weaker height, at most 2 log\u2082(n+1), with different fixup cases. AVL does not make range queries faster than a walk of the output, and an order-statistic rank needs a subtree size as well as a height.<\/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 double rotation is replaced by a single one<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Rotate right whenever the balance factor is +2<\/td>\n<td>If the left child is heavy on its right, one right rotation leaves a factor of 2 on the other side. That case is LR and needs the extra rotation first.<\/td>\n<\/tr>\n<tr>\n<td>Stop walking up after a deletion is locally repaired<\/td>\n<td>A deletion can shorten the subtree. Ancestors that were balanced can become heavy only after that shortening is visible.<\/td>\n<\/tr>\n<tr>\n<td>Balance by key order instead of by height<\/td>\n<td>The search property is already the key order. The AVL constraint is on heights. Moving the median key to the root is a different rebuild.<\/td>\n<\/tr>\n<tr>\n<td>Omit the height update on the nodes inside the rotation<\/td>\n<td>The next insert reads a stale factor and rotates the wrong way, or not at all.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A looser logarithmic binary search tree is the red-black tree, which is what many standard libraries ship. A tree that rebalances by arbitrary priorities is a treap. AVL is the height-balance rule with factors in {\u22121, 0, +1}.<\/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 restores the AVL balance factor to the set {-1, 0, +1} with the four rotations. Inserting 1, 2, 3 in that order rotates left at the root. The inorder walk is <code>1 2 3<\/code> and the root is <code>2<\/code>.<\/p>\n\n<pre><code class=\"language-python\">class N:\n    def __init__(self, key):\n        self.key, self.left, self.right, self.h = key, None, None, 1\n\ndef height(n):\n    return n.h if n else 0\n\ndef fix(n):\n    n.h = 1 + max(height(n.left), height(n.right))\n    return n\n\ndef bf(n):\n    return height(n.left) - height(n.right)\n\ndef rot_right(y):\n    x = y.left\n    y.left = x.right\n    x.right = y\n    fix(y); fix(x)\n    return x\n\ndef rot_left(x):\n    y = x.right\n    x.right = y.left\n    y.left = x\n    fix(x); fix(y)\n    return y\n\ndef balance(n):\n    n = fix(n)\n    if bf(n) &gt; 1:\n        if bf(n.left) &lt; 0:\n            n.left = rot_left(n.left)\n        return rot_right(n)\n    if bf(n) &lt; -1:\n        if bf(n.right) &gt; 0:\n            n.right = rot_right(n.right)\n        return rot_left(n)\n    return n\n\ndef insert(n, key):\n    if n is None:\n        return N(key)\n    if key &lt; n.key:\n        n.left = insert(n.left, key)\n    else:\n        n.right = insert(n.right, key)\n    return balance(n)\n\ndef inorder(n, out):\n    if n:\n        inorder(n.left, out)\n        out.append(n.key)\n        inorder(n.right, out)\n\nroot = None\nfor key in (1, 2, 3):\n    root = insert(root, key)\norder = []\ninorder(root, order)\nassert order == [1, 2, 3] and root.key == 2 and abs(bf(root)) &lt;= 1\nprint(*order, &quot;root&quot;, root.key)\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\">Windows supplies an <strong>RTL AVL table<\/strong> for in-memory indexes that want a strict height bound. The balance factor forces a rotation sooner than a red-black tree. Databases that care about disk pages use a B-tree, not an AVL tree.<\/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 AVL when a library red-black tree or a hash table already provides the required operations. Keep AVL when the worst-case height must be the tighter Fibonacci bound and the four rotation cases are acceptable code.<\/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 an AVL tree returns the balance factor, the four rotation cases, and the reason deletion keeps walking up. <strong>An AVL tree keeps every balance factor in \u22121, 0, or +1 by single and double rotations, which guarantees search, insert, and delete in O(log n) worst-case time.<\/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: An AVL tree is a binary search tree whose balance factor, left height minus right height, stays in \u22121, 0, +1 at every node. An insertion or deletion that pushes a factor to \u00b12 is repaired by a single or a double rotation. The height is 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-134","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\/134","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=134"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/134\/revisions"}],"predecessor-version":[{"id":533,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/134\/revisions\/533"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=134"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=134"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=134"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}