2-3 Trees

A 2-3 tree is a search tree with the following two properties:

Because of these properties, a 2-3 tree is a balanced tree and its height is O(log N) worst-case (where N = # of nodes).

2-3 Tree Nodes

2-3 trees have two different kinds of tree nodes, 2-nodes and 3-nodes.

2-nodes

2-nodes store one value (the key) and have a left child and a right child.  All values stored in the subtree rooted at the left child are less than the key.  All values stored in the subtree rooted at the right child are greater than the key.  (In other words, 2-nodes are the same a binary search tree nodes.)

3-nodes

3-nodes store two values (smallKey and largeKey) and have a left child, a middle child, and a right child.  All values stored in the subtree rooted at the left child are less than smallKey.  All values stored in the subtree rooted at the middle child are greater than smallKey and less than largeKey.  All values stored in the subtree rooted at the right child are greater than largeKey.

2-3 Tree Operations

"In-Order" Traversal


traverse(TwoThreeNode N)

    if N is null, return



    if N is a leaf

        visit (e.g. print) the key(s) stored in N



    else if N is a 2-node

        traverse(N.left)

        visit key

        traverse(N.right)



    else N is a 3-node

        traverse(N.left)

        visit small key

        traverse(N.middle)

        visit large key

        traverse(N.right)

Lookup Algorithm


lookup(TwoThreeNode N, Comparable value)

    if N is null, return null



    if N is a leaf

        if value is equal to (one of) the key(s) in N,

            return the key



    else if N is a 2-node

        if value < N.key    return lookup(N.left, value)

        else                return lookup(N.right, value)



    else N is a 3-node

        if value < N.smallKey  

            return lookup(N.left, value)



        else if value > N.largeKey

            return lookup(N.right, value)



        else // N.smallKey < value < N.largeKey

            return lookup(N.middle, value)

Insert Algorithm


insert(TwoThreeNode N, Comparable value)

    locate the leaf in which to put value (as in lookup)

    if the leaf is a 2-node,

        make it a 3-node

        insert value as either smallKey or largeKey



    if the leaf is a 3-node,

        insert value (temporarily) so node now has 3 keys in it:

            smallKey, middleKey, and largeKey

        split the node



split(TwoThreeNode N)

    if N is the root

        make middleKey into a 2-node (which will be the new root)

        make smallKey and largeKey into 2-nodes (which will be the 

            children of the new root)

        redistribute children



    else N has a parent P

        move middleKey up to P

        make smallKey and largeKey into 2-nodes (with parent P)

        redistribute children if necessary

        if P now has 3 keys in it, split P