Sections

Notes

Algorithm
Visualization

Homepage

### Binary Search Tree Visualization

This applet demonstrates binary search tree operations. We illustrate the operations by a sequence of snapshots during the operation. Scrolling back and forth in this sequence helps the user to understand the evolution of the search tree.

#### Operations

Our implementation supports the following tree operations:

binary tree operations

• search x
• insert x
• delete x
splay tree operations
• splay x
• splay_insert x
• splay_delete x
fast operations (with fewer snapshots)
• insert_fast x1 x2 x3 ...
• delete_fast x1 x2 x3 ...

#### Algorithm

Splay Trees were invented by Sleator and Tarjan in 1985. A splay tree is a self-adjusting binary search tree. These trees have the wonderful property to adjust optimally to any sequence of tree operations.

More precisely, a sequence of m operations on a tree with initially n leaves takes time O (n ln (n) + m ln (n)).

Also, it can be shown that for any particular sequence of operations, a splay tree is almost as good as the best binary search tree for this sequence.

A description of Splay Trees can be found here.

#### Exercises

1. Trees have the important property that the left child y of a node x has a smaller key than x. Similarly, The key of a right child z of node x is bigger than the key at x. (Observe that the nodes read from left to right are in order of increasing keys.)
Is this invariant also true at every step of each of the tree operations? Can you find the one exception?

2. Consider the effect of insert x followed by delete x on a tree T.
Can you find examples where the result is the original tree T? Is it possible to get a different tree?

3. Are delete operations commutative? (i.e. does one obtain the same tree regardless of the order in which a collection of delete operations are performed?) What about splay_delete?

4. Consider the tree on 15 nodes in the form of a linear list.
Observe the effect of splay x, where x is the key of the leaf.
Can you find a general expression for the depth-change of the tree in such cases?

5. Is it possible that the depth of a tree increases during a splay operation?

6. Consider the complete tree on 15 nodes. Can you tell which operation generates the following tree T_1? Which two operations lead to tree T_2? Use the visualizer to help.
 Tree T_1 Tree T_2

#### References

[1] Data Structures and Their Algorithms, Lewis and Denenberg, Harper Collins, 1991, pp 243-251.
[2] "Self-adjusting Binary Search Trees", Sleator and Tarjan, JACM Volume 32, No 3, July 1985, pp 652-686.
[3] Data Structure and Algorithm Analysis, Mark Weiss, Benjamin Cummins, 1992, pp 119-130.
[4] Data Structures, Algorithms, and Performance, Derick Wood, Addison-Wesley, 1993, pp 367-375

There are some other animations of binary trees on the web:

Henning Biermann, biermann@cs.nyu.edu
Revised: February 25, 1998