next up previous index
Next: Discussion Up: Binary Search Trees Previous: elementsInOrder for the NodeTree   Index

The toString method

Where possible, every class should provide a toString method, which overrides the method of the Object class. For trees, the string should indicate both the contents and the structure of the tree. For the EmptyTree class we output the empty string

public String toString() {
    return "";
}
For the NodeTree class we use the method shown in Figure 8.6.

Figure 8.6: The toString method for binary trees.
public String toString() {
    if (!left.isEmpty() && !right.isEmpty()) {
        return "(" + left + " " + data + " " + right + ")";
    } else if (!left.isEmpty()) {
        return "(" + left + " " + data + " .)";
    } else if (!right.isEmpty()) {
        return "(. " + data + " " + right + ")";
    } else {
        return data.toString();
    }
}

This is not the shortest representation but it produces strings that are reasonably clear. This prints a period ``.'' to indicate an empty left or right subtree. The tree

\begin{picture}(200,135)(-100,60)
\put(0,180){\makebox(0,0){31}}
\put(-60,120)...
...{20}}
\put(-28,72){\line(-2,3){20}}
\put(92,72){\line(-2,3){20}}
\end{picture}
will be printed as
(10 21 22) 31 (35 40 42)
since every subtree has either two or zero subtrees. The tree

\begin{picture}(200,190)(-70,0)
\put(0,180){\makebox(0,0){21}}
\put(-60,120){\...
...){20}}
\put(-12,12){\line(2,3){20}}
\put(52,12){\line(-2,3){20}}
\end{picture}
will be printed as
(10 21 ((22 31 35) 40 42))
After removing 21 using the remove method this becomes

\begin{picture}(200,190)(-70,0)
\put(0,180){\makebox(0,0){22}}
\put(-60,120){\...
...}}
% put(-12,12)\{ line(2,3)\{20\}\}
\put(52,12){\line(-2,3){20}}
\end{picture}
which will be printed as
(10 22 ((. 31 35) 40 42))
since the node storing 31 now has no left subtree.


next up previous index
Next: Discussion Up: Binary Search Trees Previous: elementsInOrder for the NodeTree   Index
Peter Williams 2005-06-07