The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Building Trees

The process of assembling tree nodes is similar to the process of assembling lists. We have a constructor for tree nodes that initializes the instance variables.

    public Tree (Object cargo, Tree left, Tree right) {
        this.cargo = cargo;
        this.left = left;
        this.right = right;

We allocate the child nodes first:

    Tree left = new Tree (new Integer(2), null, null);
    Tree right = new Tree (new Integer(3), null, null);

We can create the parent node and link it to the children at the same time:

    Tree tree = new Tree (new Integer(1), left, right);

This code produces the state shown in the previous figure.

Last Update: 2011-01-24