{"id":259,"date":"2007-01-01T13:36:05","date_gmt":"2007-01-01T13:36:05","guid":{"rendered":"http:\/\/scientopia.org\/blogs\/goodmath\/2007\/01\/01\/balanced-binary-trees-in-haskell\/"},"modified":"2007-01-01T13:36:05","modified_gmt":"2007-01-01T13:36:05","slug":"balanced-binary-trees-in-haskell","status":"publish","type":"post","link":"http:\/\/www.goodmath.org\/blog\/2007\/01\/01\/balanced-binary-trees-in-haskell\/","title":{"rendered":"Balanced Binary Trees in Haskell"},"content":{"rendered":"<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" alt=\"unbalanced-trees.jpg\" src=\"https:\/\/i0.wp.com\/scientopia.org\/img-archive\/goodmath\/img_119.jpg?resize=252%2C438\" width=\"252\" height=\"438\" class=\"inset right\" \/><\/p>\n<p>So, we&#8217;ve built up some pretty nifty binary trees &#8211; we can use the binary tree both as the<br \/>\nbasis of an implementation of a set, or as an implementation of a dictionary. But our<br \/>\nimplementation has had one major problem: it&#8217;s got absolutely no way to maintain balance. What<br \/>\nthat means is that depending on the order in which things are inserted to the tree, we might<br \/>\nhave excellent performance, or we might be no better than a linear list. For example, look at<br \/>\nthese trees.  As you can see, a tree with the same values can wind up quite different. In a good insert order, you can wind up with a nicely balanced tree: the minimum distance from root to leaf is 3; the maximum is 4. On the other hand, take the same values, and insert them in a different order and you<br \/>\nget a rotten tree; the minimum distance from root to leaf is 1, and the maximum is 7. So depending on<br \/>\nluck, you can get a tree that gives you good performance, or one that ends up giving you  no better than a plain old list.<\/p>\n<p> Today we&#8217;re going to look at fixing that problem. That&#8217;s really more of a lesson in data<br \/>\nstructures than it is in Haskell, but we&#8217;ll need to write more complicated and interesting<br \/>\ndata structure manipulation code than we have so far, and it&#8217;ll be a lollapalooza of pattern<br \/>\nmatching. What we&#8217;re going to do is turn our implementation into a <em>red-black tree<\/em>.<\/p>\n<p><!--more--><\/p>\n<p> A<br \/>\nred-black tree is a normal binary search tree, except that each node is assigned a<br \/>\n<em>color<\/em>, which is either red or black. The colored tree is maintained so that the<br \/>\nfollowing properties always hold:<\/p>\n<ol>\n<li> The root of the tree is always black.\n<li> All branches of a tree end in a null which is <em>black<\/em>.\n<li> All children or red nodes are black.\n<li> For all nodes in the tree, all downward paths from the node to a leaf contain the<br \/>\nsame number of *black* nodes.\n<\/ol>\n<p> If these invariants are maintained, they guarantee that tree is <em>almost<\/em> balanced:<br \/>\nfrom any node in the tree, the longest path from that node to a leaf is no more than twice the<br \/>\nshortest path from that node to a root. <\/p>\n<p> We&#8217;ll start by writing the Haskell type declaration for a red\/black tree. We&#8217;ll just do it<br \/>\nas a tree of ordered values to keep things simple.<\/p>\n<pre>\n&gt;data Color = Red | Black deriving (Eq, Show)\n&gt;\n&gt;data (Ord a) =&gt; RedBlackTree a = RBTNode a Color (RedBlackTree a) (RedBlackTree a)\n&gt;                            | RBTEmpty deriving (Eq,Show)\n<\/pre>\n<p> Also, for convenience, we&#8217;ll write a couple of accessor functions that we&#8217;ll<br \/>\nuse later on. Something interesting to note about these accessors is that they use<br \/>\n<em>non-exhaustive patterns<\/em>: there are values of type <code>RedBlackTree a<\/code><br \/>\nfor which these functions are undefined. If you call the function on one of those<br \/>\nvalues, you&#8217;ll get a runtime error. It&#8217;s generally considered bad style to write<br \/>\nnon-exhaustive functions like this, but the best solution to that would<br \/>\nbe to use <code>Maybe<\/code> types, and they&#8217;ll have a nasty impact on the<br \/>\ncomplexity of some of the code later, we won&#8217;t worry about that for now; I&#8217;ll explain<br \/>\nhow to fix that up in a future post, when we get to monads.<\/p>\n<pre>\n&gt;\n&gt;rbtLeftChild :: (Ord a) =&gt; RedBlackTree a -&gt; RedBlackTree a\n&gt;rbtLeftChild (RBTNode _ _ l _) = l\n&gt;\n&gt;rbtRightChild :: (Ord a) =&gt; RedBlackTree a -&gt; RedBlackTree a\n&gt;rbtRightChild (RBTNode _ _ _ r) = r\n&gt;\n&gt;rbtValue :: (Ord a) =&gt; RedBlackTree a -&gt; a\n&gt;rbtValue (RBTNode v _ _ _) =  v\n&gt;\n&gt;rbtColor :: (Ord a) =&gt; RedBlackTree a -&gt; Color\n&gt;rbtColor (RBTNode _ c _ _) = c\n&gt;rbtColor RBTEmpty = Black\n<\/pre>\n<p> Inserting data into the tree is where things get interesting. You start by doing<br \/>\n<em>basically<\/em> the same thing you did in the simple binary search tree; the only<br \/>\ndifference is that the node needs a color. New nodes are always <em>red<\/em>. Once we&#8217;ve done<br \/>\nthat initial part of the insert, we need to verify that all of the invariants hold. If not,<br \/>\nwe&#8217;ll need to fix the tree. To keep things reasonably clean and separate, we&#8217;ll use the<br \/>\ntail-calling version of tree insert that I showed in <a href=\"http:\/\/scientopia.org\/blogs\/goodmath\/2006\/12\/tail-recursion-iteration-in-haskell\">this post<\/a>, and<br \/>\nthen tail-call a rebalance function when the basic insert is complete. Rebalance will<br \/>\nfix the balance of the tree, and do the tree re-assembly as it climbs up the tree.<\/p>\n<pre>\n&gt;rbtInsert :: (Ord a) =&gt; RedBlackTree a -&gt; a -&gt; RedBlackTree a\n&gt;rbtRebalance :: (Ord a) =&gt; RedBlackTree a -&gt; [RedBlackTree a] -&gt; RedBlackTree a\n&gt;--rbtRebalance               focus              ancestors\n&gt;\n&gt;rbtInsert node v =\n&gt;    rbtInsertTailCall node v []\n&gt;\n&gt;rbtInsertTailCall node@(RBTNode v color left right) newval path\n&gt;             | v &gt; newval = rbtInsertTailCall left newval (node:path)\n&gt;             | otherwise = rbtInsertTailCall right newval (node:path)\n&gt;rbtInsertTailCall RBTEmpty v path =\n&gt;    \trbtRebalance (RBTNode v Red RBTEmpty RBTEmpty) path\n<\/pre>\n<p>  All over the place as we rebalance the tree, we&#8217;ll have places where we want to<br \/>\n&#8220;rebuild&#8221; nodes to patch in the insertion change; as usual, we separate that into<br \/>\nits own function.\n<\/p>\n<pre>\n&gt;-- Reconstruct takes a child node and a parent node, and creates a replacement\n&gt;-- for the parent node with the child in the appropriate position. It allows\n&gt;-- the color of the new node to be specified.\n&gt;reconstructNode node@(RBTNode v c l r) parent@(RBTNode pv pc pl pr) color =\n&gt;   if (pv &gt; v)\n&gt;      then (RBTNode pv color node pr)\n&gt;      else (RBTNode pv color pl node)\n<\/pre>\n<p> Now, we need to think about what we&#8217;re going to do to keep the tree balanced as we walk<br \/>\nback up the insertion path fixing the tree. There are two things we can do to make the<br \/>\ntree respect the invariants: we can re-color nodes, or we can <em>pivot<\/em> subtrees.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" alt=\"unbalanced-tree.jpg\" src=\"https:\/\/i0.wp.com\/scientopia.org\/img-archive\/goodmath\/img_120.jpg?resize=198%2C170\" width=\"198\" height=\"170\" class=\"inset right\" \/><\/p>\n<p> Pivoting a tree is an interesting operation &#8211; it&#8217;s a process of swapping a node and one of<br \/>\nits children to rotate a section of the tree. Suppose we have a binary search tree like the one<br \/>\nin the diagram to the side. It&#8217;s poorly balanced; it&#8217;s got only one node to its left, but 7<br \/>\nnodes to its right. To correct this by pivoting, what we&#8217;ll do is take node 6 &#8211; currently a<br \/>\nchild of the root, and rotate the tree counterclockwise around it, so that 6 becomes the root,<br \/>\nthe old root (2) becomes the left child of 6, and the old left child of 6 (node 4) becomes the<br \/>\n<em>right<\/em> child of the old root. <\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" alt=\"balanced.jpg\" src=\"https:\/\/i0.wp.com\/scientopia.org\/img-archive\/goodmath\/img_409.jpg?resize=220%2C175\" width=\"220\" height=\"175\" class=\"inset right\" \/><\/p>\n<p> So after the pivot, our tree looks like this. This<br \/>\noperation was a <em>left<\/em> pivot; a right pivot does the same kind of thing, but rotating<br \/>\nthe tree clockwise instead of counterclockwise. <\/p>\n<p> So let&#8217;s go ahead and write the pivot operations. We&#8217;ll write two pivot<br \/>\nfunctions: one for each direction. We&#8217;ll pass the pivot operation<br \/>\na subtree whose root and child in the appropriate direction are to be rotated. In addition,<br \/>\nwe&#8217;ll also add a parameter for managing the color of the new root node. In some cases,<br \/>\nwe&#8217;ll want to swap the colors of the nodes being moved; in other cases, we won&#8217;t. So we&#8217;ll<br \/>\nput a boolean parameter in to specify whether or not to swap the colors.<\/p>\n<pre>\n&gt; -- pivot left tree at root; second parent indicates whether or not to swap\n&gt; -- colors of the nodes that are being moved.\n&gt;rbtPivotLeft :: (Ord a) =&gt; RedBlackTree a -&gt; Bool -&gt; RedBlackTree a\n&gt;rbtPivotLeft (RBTNode rootval rootcolor sib (RBTNode focval foccolor focleft focright)) swap =\n&gt;       (RBTNode focval newrootcolor oldroot focright) where\n&gt;             newrootcolor = if swap then rootcolor else foccolor\n&gt;             oldrootcolor = if swap then foccolor else rootcolor\n&gt;             oldroot = RBTNode rootval oldrootcolor sib focleft\n&gt;\n&gt;\n&gt;rbtPivotRight (RBTNode rootval rootcolor (RBTNode focval foccolor focleft focright) sib) swap =\n&gt;       (RBTNode focval newrootcolor focleft oldroot) where\n&gt;             newrootcolor = if swap then rootcolor else foccolor\n&gt;             oldrootcolor = if swap then foccolor else rootcolor\n&gt;             oldroot = RBTNode rootval oldrootcolor focright sib\n&gt;\n<\/pre>\n<p> So, let&#8217;s try taking a look at how the pivots work. First, we need to construct<br \/>\nsome trees to rebalance. We&#8217;ll just do it manually, since the insert code isn&#8217;t properly<br \/>\nfinished yet.<\/p>\n<pre>\n&gt;twentyseven = RBTNode 27 Black RBTEmpty RBTEmpty\n&gt;twentytwo = RBTNode 22 Black RBTEmpty RBTEmpty\n&gt;twentyfive = RBTNode 25 Black twentytwo twentyseven\n&gt;sixteen = RBTNode 16 Black RBTEmpty RBTEmpty\n&gt;twenty = RBTNode 20 Black sixteen twentyfive\n&gt;twelve = RBTNode 12 Black RBTEmpty RBTEmpty\n&gt;fifteen = RBTNode 15 Black twelve twenty\n&gt;two = RBTNode 2 Black RBTEmpty RBTEmpty\n&gt;seven = RBTNode 7 Black RBTEmpty RBTEmpty\n&gt;five = RBTNode 5 Black two seven\n&gt;ten = RBTNode 10 Black five fifteen\n<\/pre>\n<p> That produces a unbalanced binary tree that looks like this:<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" alt=\"test-balance-before.jpg\" src=\"https:\/\/i0.wp.com\/scientopia.org\/img-archive\/goodmath\/img_122.jpg?resize=186%2C141\" width=\"186\" height=\"141\" class=\"inset\" \/><\/p>\n<pre>\nRBTNode 10 Black\n(RBTNode 5 Black -- 10left\n(RBTNode 2 Black RBTEmpty RBTEmpty)  -- 5 left\n(RBTNode 7 Black RBTEmpty RBTEmpty)) -- 5 right\n(RBTNode 15 Black -- 10 right\n(RBTNode 12 Black RBTEmpty RBTEmpty) -- 15 left\n(RBTNode 20 Black  -- 15 right\n(RBTNode 16 Black RBTEmpty RBTEmpty) -- 20 left\n(RBTNode 25 Black -- 20 right\n(RBTNode 22 Black RBTEmpty RBTEmpty) -- 25 left\n(RBTNode 27 Black RBTEmpty RBTEmpty)))) -- 25 right\n<\/pre>\n<p> Let&#8217;s do a quick test, and try doing a left pivot on the root.<\/p>\n<pre>\n*Main&gt; rbtPivotLeft ten False\nRBTNode 15 Black (RBTNode 10 Black (RBTNode 5 Black (RBTNode 2 Black RBTEmpty RBTEmpty) (RBTNode 7 Black RBTEmpty RBTEmpty)) (RBTNode 12 Black RBTEmpty RBTEmpty)) (RBTNode 20 Black (RBTNode 16 Black RBTEmpty RBTEmpty) (RBTNode 25 Black (RBTNode 22 Black RBTEmpty RBTEmpty) (RBTNode 27 Black RBTEmpty RBTEmpty)))\n*Main&gt;\n<\/pre>\n<p> Cleaned up, that looks like this: <\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" alt=\"test-balance-after.jpg\" src=\"https:\/\/i0.wp.com\/scientopia.org\/img-archive\/goodmath\/img_410.jpg?resize=183%2C103\" width=\"183\" height=\"103\" class=\"inset right\" \/><\/p>\n<pre>\nRBTNode 15 Black\n(RBTNode 10 Black\n(RBTNode 5 Black\n(RBTNode 2 Black RBTEmpty RBTEmpty)\n(RBTNode 7 Black RBTEmpty RBTEmpty))\n(RBTNode 12 Black RBTEmpty RBTEmpty))\n(RBTNode 20 Black\n(RBTNode 16 Black RBTEmpty RBTEmpty)\n(RBTNode 25 Black\n(RBTNode 22 Black RBTEmpty RBTEmpty)\n(RBTNode 27 Black RBTEmpty RBTEmpty)))\n<\/pre>\n<p> Much better &#8211; that&#8217;s much closer to a balanced tree! So now that we know how to do the<br \/>\npivot, and we&#8217;ve seen that it works correctly, we can look at building the rebalance code.\n<\/p>\n<p> With pivots out of the way, we can start looking at how to decide what<br \/>\noperations to do to rebalance the tree.  When we&#8217;re doing an insert, we end up inserting a red node on the bottom of the tree.<br \/>\nIt&#8217;s got two children, both null, which are considered black. If the parent of our new node is<br \/>\nblack, then everything is fine; we haven&#8217;t altered the number of black nodes on any path from<br \/>\na node to a leaf. So we&#8217;re done. But if the parent is red, then we&#8217;ve got a red child of a red<br \/>\nnode, so we need to do some fixing.<\/p>\n<p> Fixing an imbalance in a red-black tree can (and in fact often will) trigger a cascade of<br \/>\nchanges. But in each case, we can look at the specific problem, and fix it, and we&#8217;ll always<br \/>\nknow exactly where the next potential problem is. So we&#8217;ll look at it in terms of a <em>focal<br \/>\nnode<\/em>, which is the node causing the immediate problem we&#8217;re fixing.<\/p>\n<p> The potential cases we can encounter are:<\/p>\n<ol>\n<li> The focal node is the root of the tree. In that case, we make it black. That adds<br \/>\non black node to every path in the tree, which leaves us with a valid tree, so we&#8217;re<br \/>\ndone.<\/li>\n<li> The focal node is red, but has a black parent. Again, that&#8217;s fine. No problem.<\/li>\n<li> The focal node is red; it&#8217;s parent is also red. Then we need to look at its <em>uncle<\/em>; that is, the node that is the sibling of its parent. If both the new node, the parent and the uncle are all red, then we change the color of the parent and uncle to black,<br \/>\nand the grandparent to red. After this, the grandparent becomes the focal node, and we continue to do our tree-fixing with the new focus.<\/li>\n<li> Here&#8217;s where it gets a bit messy &#8211; figuring out the correct pivots. If the focal node and its parent are both red, and the uncle is black, then we need to do a pivot.\n<ol>\n<li> The focal node is the <em>right<\/em> child of its parent, and the parent is the <em>left<\/em> node of the grandparent, then we do a <em>left<\/em> pivot of the focal node and its parent, and the former parent becomes the new focal node.<\/li>\n<li> The focal node is the <em>left<\/em> child of its parent, and the parent is the <em>right<\/em> child of the grandparent, then we do a <em>right<\/em> pivot of the focal node and its parent, and the former parent becomes the new focus.<\/li>\n<li> The focal node is the left child of its parent, and the parent is the left child of the grandparent. Then we do a <em>right<\/em> pivot of the parent and the grandparent and swap the colors of the parent and grandparent. The parent becomes the focus. <\/li>\n<li> The focal node is the right child of its parent, and the parent is the right child of the grandparent. Then we do a <em>left<\/em> pivot of the parent and the grandparent and swap the colors of the parent and grandparent. The parent becomes the focus. <\/li>\n<\/ol>\n<\/ol>\n<p> Ok, there&#8217;s the algorithm for rebalancing. How can we code it in Haskell? We&#8217;ve got a list<br \/>\nof the nodes from the insertion path, in leaf to root order.  When we look at the rebalance, we can see that there are a bunch of different cases<br \/>\nwhich we can separate via pattern matching:<\/p>\n<ol>\n<li> The focus is the root of the tree. We can select this case by using<br \/>\nan empty list for the pattern for the ancestors parameter. Once we&#8217;ve gotten to<br \/>\nthe root, the tree is balanced, and the only corrective thing we may need to<br \/>\ndo is make the root black. So:<\/p>\n<pre>\n&gt;-- Root is focus; no matter what color it is, just make it black\n&gt;rbtRebalance (RBTNode v _ left right) [] = RBTNode v Black left right\n&gt;rbtRebalance node@(RBTNode v _ left right) (parent@(RBTNode pv pc pl pr):[])\n&gt;                        | pv &gt; v = RBTNode pv pc node pr\n&gt;      \t                 | otherwise = RBTNode pv pc pl node\n<\/pre>\n<\/li>\n<li> Also very simple is the case where the focus is black. In that case, we don&#8217;t<br \/>\nneed to do anything except patch in the insert, and continue up the tree.<\/p>\n<pre>\n&gt;-- black node - just patch in the change, and climb.\n&gt;\n&gt;rbtRebalance focus@(RBTNode fv Black left right) (parent@(RBTNode pv pc pl pr):ancestors)\n&gt;            | pv &gt; fv = rbtRebalance (RBTNode pv pc focus pr) ancestors\n&gt;      \t     | otherwise = rbtRebalance (RBTNode pv pc pl focus) ancestors\n&gt;\n<\/pre>\n<\/li>\n<li> Next, we&#8217;ve got the case of a red node with a black parent. We can identify it by using<br \/>\n&#8220;<code>RBTNode v Red left right\" as a pattern for the focus, and \"<code>RBTNode _ Black _<br \/>\n_<\/code>\" as a pattern for the parent. A red node with a black parent is OK, as long as the<br \/>\nsubtree under the red is balanced; and since we're balancing from the bottom up, we know that<br \/>\neverything beneath this node is balanced. So:<\/p>\n<pre>\n&gt;rbtRebalance focus@(RBTNode fv Red left right) (parent@(RBTNode pv Black pl pr):ancestors) =\n&gt;           rbtRebalance (reconstructNode focus parent Black) ancestors\n<\/pre>\n<\/li>\n<li> Now we're getting to the interesting cases, which are the cases where both the node and its parent are red. We can separate two cases here: cases where we'll fix using a pivot,<br \/>\nand cases where we'll fix using a recoloring. The way to distinguish them is by looking at<br \/>\nthe <em>uncle<\/em> of the focus node; that is, the sibling of the nodes parent. The red-red<br \/>\ncase is complicated enough that instead of writing out huge pattern expressions, we'll<br \/>\nsimplify it by separating the function into several layers of calls, each of which<br \/>\ndoes a phase of the pattern match. We want to separate out the cases where we've<br \/>\ngot a red node with a red parent and a red uncle, and the cases where we've got<br \/>\na red node with a red parent and a black uncle.<\/p>\n<p> If the focus, its parent, and its uncle are all red, then we're in a recoloring case; if<br \/>\nthe focus and its parent are red, and the uncle is black, then we're in a pivot case.<\/p>\n<pre>\n&gt;rbtRebalance focus@(RBTNode v Red left right) (parent@(RBTNode _ Red _ _):ancestors) =\n&gt;    rebalanceRedRedNode focus parent ancestors\n<\/pre>\n<p> To be able to recognize sub-cases when we have a red node\/red parent, we need<br \/>\nto be able to look at the path from the grandparent to the focus, and the color of the uncle. So<br \/>\nwe'll write some helper functions to get those. <\/p>\n<pre>\n&gt;uncleColor node parent grandparent =\n&gt;    if (parent == rbtLeftChild grandparent)\n&gt;        then rbtColor (rbtRightChild grandparent)\n&gt;        else rbtColor (rbtLeftChild grandparent)\n&gt;\n&gt;data TwoStepPath = LeftLeft | LeftRight | RightLeft | RightRight\n&gt;\n&gt;pathFromGrandparent :: (Ord a) =&gt; RedBlackTree a -&gt; RedBlackTree a -&gt; RedBlackTree a -&gt; TwoStepPath\n&gt;pathFromGrandparent node@(RBTNode v _ l r) parent@(RBTNode pv _ pl pr) grand@(RBTNode gv _ gl gr)\n&gt;        | pv &lt; gv  &amp;&amp; v         | pv &gt;= gv &amp;&amp; v         | pv = pv = LeftRight\n&gt;        | pv &gt;= gv &amp;&amp; v &gt;= pv = RightRight\n<\/pre>\n<p> To actually handle the red node\/red parent, first we separate out the<br \/>\ncase where the red parent is the root of the tree - there are no more ancestors<br \/>\non the insertion path. In that case, we can just climb to root, and do the correction<br \/>\nfrom there.&lt;\/p<\/p>\n<pre>\n&gt;\n&gt;-- node is red, parent is red, but parent is root: just go to parent(root), and fix\n&gt;-- from there.\n&gt;rebalanceRedRedNode focus@(RBTNode fv fc fl fr) parent@(RBTNode pv pc pl pr) [] =\n&gt;      rbtRebalance (reconstructNode focus parent Red) []\n<\/pre>\n<p> Otherwise, we need to check whether the uncle was red or black. If it was black,<br \/>\nwe do a recolor correction; if it was red, we figure out what kind of pivot to do. We'll<br \/>\nuse a bunch of helper function to make it easy.<\/p>\n<pre>\n&gt;rebalanceRedRedNode focus parent (grand@(RBTNode gv gc gl gr):ancestors) =\n&gt;    if (uncleColor focus parent grand) == Red\n&gt;        then recolorAndContinue focus parent grand ancestors\n&gt;    else case (pathFromGrandparent focus parent grand) of\n&gt;             LeftLeft -&gt; rbtRebalance (pivotGrandparentRight focus parent grand) ancestors\n&gt;             LeftRight -&gt; rbtRebalance (pivotParentLeft focus parent) (grand:ancestors)\n&gt;             RightLeft -&gt; rbtRebalance (pivotParentRight focus parent) (grand:ancestors)\n&gt;             RightRight -&gt; rbtRebalance (pivotGrandparentLeft focus parent grand) ancestors\n<\/pre>\n<p> The code above is really just using patterns for case selection. The actual work is in the<br \/>\nhelper functions that get called. They're all simple functions. First, we have some custom<br \/>\npivot functions - one for each direction for pivoting around a parent (the cases where the<br \/>\nnode is left of the parent, and the parent is right of the grandparent, or vise versa), and<br \/>\none for each direction pivoting around a grandparent (both node and parent are left children, or both are<br \/>\nright children).<\/p>\n<pre>\n&gt;pivotGrandparentLeft node parent@(RBTNode pv pc pl pr) grand@(RBTNode gv gc gl gr) =\n&gt;     rbtPivotLeft  (RBTNode gv gc gl (RBTNode pv pc pl node)) True\n&gt;\n&gt;pivotGrandparentRight node parent@(RBTNode pv pc pl pr) grand@(RBTNode gv gc gl gr) =\n&gt;     rbtPivotRight  (RBTNode gv gc (RBTNode pv pc node pr) gr) True\n&gt;\n&gt;pivotParentLeft node parent@(RBTNode pv pc pl pr) =\n&gt;     rbtPivotLeft (RBTNode pv pc pl node) False\n&gt;\n&gt;pivotParentRight node parent@(RBTNode pv pc pl pr) =\n&gt;    rbtPivotRight (RBTNode pv pc node pr) False\n<\/pre>\n<p> And a function to do the recoloring for when the uncle was red:<\/p>\n<pre>\n&gt;recolorAndContinue focus@(RBTNode v c l r) parent@(RBTNode pv pc pl pr) grand@(RBTNode gv gc gl gr) ancestors =\n&gt;      let path = pathFromGrandparent focus parent grand\n&gt;          uncle = (case path of\n&gt;                    LeftLeft -&gt; gr\n&gt;                    LeftRight -&gt; gr\n&gt;                    RightLeft -&gt; gl\n&gt;                    RightRight -&gt; gl)\n&gt;          newUncle = if (uncle == RBTEmpty)\n&gt;                         then RBTEmpty\n&gt;                         else (RBTNode (rbtValue uncle) Black (rbtLeftChild uncle) (rbtRightChild uncle))\n&gt;          newparent = reconstructNode focus parent Black\n&gt;          newGrandParent = (case path of\n&gt;              LeftLeft -&gt; (RBTNode gv Red newparent newUncle)\n&gt;              LeftRight -&gt; (RBTNode gv Red newparent newUncle)\n&gt;              RightLeft -&gt; (RBTNode gv Red newUncle newparent)\n&gt;              RightRight -&gt; (RBTNode gv Red newUncle newparent))\n&gt;          in rbtRebalance newGrandParent ancestors\n<\/pre>\n<\/li>\n<\/ol>\n<p> And that, finally, is it. For the binary search tree without balancing code, the<br \/>\nworst case is inserting a list of values in order. So let's try that, to see how<br \/>\nwell this works.<\/p>\n<pre>\n*Main&gt; foldl ( x y -&gt; rbtInsert x y) RBTEmpty [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n11, 12, 13, 14, 15, 16]\nRBTNode 4 Black (RBTNode 2 Black (RBTNode 1 Black RBTEmpty RBTEmpty) (RBTNode 3 Black RBTEmpty RBTEmpty))\n(RBTNode 8 Red (RBTNode 6 Black (RBTNode 5 Black RBTEmpty RBTEmpty) (RBTNode 7 Black RBTEmpty RBTEmpty))\n(RBTNode 12 Black (RBTNode 10 Red (RBTNode 9 Black RBTEmpty RBTEmpty) (RBTNode 11 Black RBTEmpty RBTEmpty))\n(RBTNode 14 Red (RBTNode 13 Black RBTEmpty RBTEmpty) (RBTNode 15 Black RBTEmpty (RBTNode 16 Red RBTEmpty RBTEmpty)))))\n<\/pre>\n<p> Since that's completely illegible, let's clean it up, and look at it in picture form:\n<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" alt=\"result-tree.jpg\" src=\"https:\/\/i0.wp.com\/scientopia.org\/img-archive\/goodmath\/img_124.jpg?resize=298%2C189\" width=\"298\" height=\"189\" class=\"inset right\" \/><\/p>\n<p> The shortest path from root to leaf is [4,2,1]; the longest is [4,8,12,14,15,16]. Just<br \/>\nlike we promised: the longest is no more than twice the shortest. It's a pretty good<br \/>\nsearch tree, and the rebalancing work isn't terribly expensive, and amortizes nicely<br \/>\nover a long run of inserts. The insert time ends up amortizing to **O**(lg n), just like the simple<br \/>\nbinary search tree insert.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>So, we&#8217;ve built up some pretty nifty binary trees &#8211; we can use the binary tree both as the basis of an implementation of a set, or as an implementation of a dictionary. But our implementation has had one major problem: it&#8217;s got absolutely no way to maintain balance. What that means is that depending [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[89],"tags":[],"class_list":["post-259","post","type-post","status-publish","format-standard","hentry","category-haskell"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p4lzZS-4b","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts\/259","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/comments?post=259"}],"version-history":[{"count":0,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts\/259\/revisions"}],"wp:attachment":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/media?parent=259"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/categories?post=259"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/tags?post=259"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}