Rice University - Comp 212 - Intermediate Programming

Spring 2002

Lecture #23 - Binary Tree Structure


Up until now, we have been organizing data in a "linear" fashion: one item after another.  The corresponding data structures are the immutable scheme list (AList) and the mutable linear recursive structure (LRStruct).  Now, suppose we want to model something like the following organization chart.

A structure of data such as the above is called a tree.  We first design a special kind of mutable tree structure called binary trees.

1. Binary Tree Object Model

A (mutable) binary tree, BiTree, can be in an empty state or a non-empty state.  

We implement the above object structure with a combination of state/composite/visitor patterns, in a manner analogous to LRStruct.

Below is the public interface of the binary tree framework.  Click here for javadoc documentation.

The implementation details are given in the following UML class diagram.  Click here for javadoc documentation.

 

2. Implementation Details

Click here for source code.

The code for BiTree is trivial, as it simply delegates most calls to its state, the root node.  The real work is done in the state.  The code for EmptyNode and DatNode for the most part are equally trivial.  The insertion and removal of the root data of a BiTree require some work and need some explanation.  Does it make sense to remove the root node from a (binary) tree?  May be!

EmptyNode

DatNode


    /**
    * Asks the owner tree to set the root node to a new
    * DatNode containing dat,
    * resulting in a state change from empty to non-empty.
    * @param dat a given data Object.
    * @param owner the context of this state.
    */
    void insertRoot(Object dat, BiTree owner) {
        owner.setRootNode(new DatNode(dat));
    }

    /**
    * Throws java.util.NoSuchElementException.
    * @param owner the BiTree holding this EmptyNode.
    */
    Object remRoot (BiTree owner) {
        throw new NoSuchElementException ("EmptyNode.remRoot()");
    }

class DatNode extends ANode {
    /**
     * Data Invariant: != null.
     */
    private BiTree _leftTree = new BiTree ();
    /**
    * the stored data element.
    */
    private Object _dat;
    /**
    * Data Invariant: != null.
    */
    private BiTree _rightTree = new BiTree ();

    /**
    * Throws an IllegalStateException because the owner tree is not empty.
    * @exception IllegaStateException.
    */
    void insertRoot(Object dat, BiTree owner) {
        throw new IllegalStateException ("DatNode.insertRoot().");
    }

    /**
    * Removes and returns the root element from the owner tree by asking the
    * left and the right subtrees to help do the job.  The subtrees help
    * determine whether or not the root element can be removed by executing
    * appropriate anonymous visitors.
    * @param owner the BiTree holding this DatNode.  Why is it final?
    * @exception IllegaStateException if the owner has a non-empty subtree.
    */
    Object remRoot(final BiTree owner) {
        return _leftTree.execute(new IVisitor() {

            /**
             * The left subtree is empty. It is now up to the right subtree
             * to determine whether or not the root element can be removed.
             */
            public Object emptyCase(BiTree host, Object inp) {
                return _rightTree.execute(new IVisitor() {

                    /**
                     * At this point both the lef and right subtrees are empty.
                     */
                    public Object emptyCase(BiTree h, Object nu) {
                        owner.setRootNode(EmptyNode.Singleton);
                        return _dat;
                    }

                    /**
                    * The right subtree is not empty!  This DatNode is not a leaf!
                    */
                    public Object nonEmptyCase(BiTree h, Object nu) {
                        throw new IllegalStateException ("Not a leaf.");
                    }
                }, null);
            }

            /**
             * The left subtree is not empty!  This DatNode is not a leaf!
             */
            public Object nonEmptyCase(BiTree host, Object inp) {
                throw new IllegalStateException ("Not a leaf.");
            }
        }, null);
    }


}

 
 

 

3. The Best Tree Printing Algorithm in Texas

The following visitor and its helper print a binary "vertically" as shown below..

-7
|_ -55
| |_ []
| |_ -16
| |_ -20
| | |_ []
| | |_ []
| |_ -9
| |_ []
| |_ []
|_ 0
|_ -4
| |_ []
| |_ []
|_ 23
|_ []
|_ []

Let's study the algorithm.

   
/**
 * Computes a String representation of the binary tree host so
 * that it can be
 * printed vertically.
 * @author Dung X. Nguyen - Copyright 2000 - All rights reserved.
 */
public class ToString implements IVisitor {
	public final static ToString Singleton = new ToString ();

    private ToString () {
    }

    /**
     * Returns "[]", a String representation of an empty binary
     * tree.
     * @param host an empty binary tree.
     * @param nu not used.
     * @return String
    */
    public Object emptyCase(BiTree host, Object nu) {
        return "[]";
    }

    /**
     * Computes a String representation of the binary tree host
     * so that it can be printed vertically. There is no '\n'
     * at the end of the String.  Passes appropriate leftmost
     * leading String to a
     * helper visitor to compute the
     * String representations of the left and right subtrees.
     * @param host a non-empty binary tree.
     * @param nu not used.
     * @return String
     */
    public Object nonEmptyCase(BiTree host, Object nu) {
        String ls
        = (String)host.getLeftSubTree().execute(ToStringHelp.Singleton,
								"|  ");
        String rs
        = (String)host.getRightSubTree().execute(ToStringHelp.Singleton,
								"   ");
        return (host.getRootDat() + "\n" + ls + "\n" + rs);
        // EXERCISE FOR STUDENTS: Rewrite using anonymous inner classes.
    }
}
/**
 * Computes a String representation of the binary tree host so 
 * that it can be printed vertically, given a leftmost leading
 * string for the two subtrees.
 * Called by ToString.
 * Should be implemented as an anonymous inner class in the 
 * call by ToString.
 * @author Dung X. Nguyen - Copyright 2001 - All rights reserved.
 */
public class ToStringHelp implements IVisitor {
    public final static ToStringHelp Singleton = new ToStringHelp ();
    private ToStringHelp () {
    }

    /**
    * Returns "|_[]" to denote an empty tree subtree.
    * @param host an empty binary (sub)tree.
    * @param nu not used.
    * @return String
    */
    public Object emptyCase(BiTree host, Object nu) {
        return "|_ []";
    }

    /**
    * Computes a String representation of the binary tree host 
    * so that it can be printed vertically.
    * There is no '\n' at the end of the String.
    * @param host a non-empty binary (sub)tree.
    * @param leftLead appropriate leftmost leading String to
    * help compute the
    * String representations of the left and right subtrees.
    * @return String
    */
    public Object nonEmptyCase(BiTree host, Object leftLead) {
        String ls
            = (String)host.getLeftSubTree().execute(this, 
                                              	leftLead + "|  ");
        String rs
            = (String)host.getRightSubTree().execute(this,
      						leftLead + "   ");
        return ("|_ " + host.getRootDat()+ "\n" +
                leftLead + ls + "\n" +
                leftLead + rs);
    }
}
   




 


dxnguyen@cs.rice.edu
Copyright 2002, Dung X. Nguyen - All rights reserved.