The C++Course provides a general introduction to programming in C++. 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 (int cargo, Tree* left, Tree* right) {
        this->cargo = cargo;
        this->left = left;
        this->right = right;
    }

We allocate the child nodes first:

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

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

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

This code produces the state shown in the previous figure.


Last Update: 2005-12-05