Comp 212: Intermediate Programming

Fall 2001

Lecture #33: 2-3-4 Tree


Definition

A 2-3-4 tree is a container of data that can be compared by a total ordering relation.   For the sake of definiteness, we can assume without loss of generality that the data in concern are integers.  A 2-3-4 tree can be empty or not empty. 

Self-balancing Tree

Starting from an empty 2-3-4 tree, we want to be able to add elements to the tree in such a way that not only the 2-3-4 tree property is maintained but also all the subtrees at the same level are balanced, i.e. have the same height.  This balance property permits a O(logN) lookup operation, where N is the number of elements in the tree.   The following insertion algorithm achieves this goal.


Insertion Algorithm

Let T be a 2-3-4 tree.  The main idea behind inserting an integer N into T is as follow: go down the search path for N in the tree, and insert it into the appropriate leaf; along the search path, if a 4-state tree is encountered, split it into a 2-state tree and merge it with its parent tree (if any) before inserting N. The insertion of N into T involves the following cases.

  1. The empty case: T changes to a 2-state tree containing N, an empty left subtree and an empty right subtree.

  2. The 2-state case: [lst, X, rst]

  3. The 3-state case: [lst, X, mst, Y, rst]

  4. The 4-state case: [lst, X, mlst, Y, mrst, Z, rst]

The 2-3-4 tree with the above insertion algorithm can be implemented using the state pattern as shown in the following UML diagram.

 

Author: Dung X. Nguyen

Last revised 11/12/01

Copyright 2001 - All rights reserved.