8. Scapegoat Trees

In this chapter, we study a binary search tree data structure, the ScapegoatTree. This structure is based on the common wisdom that, when something goes wrong, the first thing people tend to do is find someone to blame (the scapegoat). Once blame is firmly established, we can leave the scapegoat to fix the problem.

A ScapegoatTree keeps itself balanced by partial rebuilding operations. During a partial rebuilding operation, an entire subtree is deconstructed and rebuilt into a perfectly balanced subtree. There are many ways of rebuilding a subtree rooted at node $ \ensuremath{\ensuremath{\mathit{u}}}$ into a perfectly balanced tree. One of the simplest is to traverse $ \ensuremath{\ensuremath{\mathit{u}}}$'s subtree, gathering all its nodes into an array, $ \ensuremath{\ensuremath{\mathit{a}}}$, and then to recursively build a balanced subtree using $ \ensuremath{\ensuremath{\mathit{a}}}$. If we let $ \ensuremath{\ensuremath{\ensuremath{\mathit{m}}}}=\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}/2$, then the element $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{m}}]}$ becomes the root of the new subtree, $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}[0],\ldots,\ensuremath{\ensur...
...{\ensuremath{\mathit{a}}}}[\ensuremath{\ensuremath{\ensuremath{\mathit{m}}}}-1]$ get stored recursively in the left subtree and $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}[\ensuremath{\ensuremath{\ens...
...hit{a}}}}[\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}-1]$ get stored recursively in the right subtree.
\hspace*{1em} \ensuremath{\mathrm{rebuild}(\en...
A call to $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$ takes $ O(\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}})$ time. The resulting subtree has minimum height; there is no tree of smaller height that has $ \ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}$ nodes.