# Introduction to Scapegoat Trees

Learn how to implement Scapegoat trees in this lesson.

We'll cover the following

## Scapegoat trees overview

Here, 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 u into a perfectly balanced tree. One of the simplest is to traverse u’s subtree, gathering all its nodes into an array, a, and then to recursively build a balanced subtree using a. If we let $m = \text{a.length}/2$, then the element a[m] becomes the root of the new subtree, a$[0],...,\text{a}[m−1]$ get stored recursively in the left subtree and $\text{a}[m + 1],...,\text{a}[\text{a.length} − 1]$ get stored recursively in the right subtree.