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.
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();
}
}
|
(10 21 22) 31 (35 40 42)since every subtree has either two or zero subtrees. The tree
(10 21 ((22 31 35) 40 42))After removing 21 using the remove method this becomes
(10 22 ((. 31 35) 40 42))since the node storing 31 now has no left subtree.