Balancing Rotations in Binary Search Trees

A binary search tree could be defined by the following data declaration in Haskell

data Tree a
   = Tip
   | Node (Tree a) a (Tree a)

To be a binary search tree it must maintain the search invariant. For every (Tree a) of shape (Node left x right) the elements of type a in left must be less than x, and the elements of type a in right must be greater than or equal to x.

A tree that meets the search invariant can be transformed into an equivalent tree that also meets the invariant by a process called rotation. This is best understod by the diagram below.

?

We can capture the left to right transformation by the function:

rotR (Node (Node a x b) y c) = (Node a x (Node b y c))

We can capture the right to left transformation by the function:

rotR (Node a x (Node b y c)) = (Node (Node a x b) y c)

Note that the transformed tree maintains the invariant, and

search m x  ==  search m (rotR x)  == search m (rotL x)
Back to the Daily Record.

Back to the class web-page.