interface Tree
{
public boolean contains
(String word
);
public int size();
}
class EmptyTree implements Tree
{
{
return new Leaf(word);
}
public boolean contains
(String word
) {
return false;
}
public int size()
{
return 0;
}
{
return "()";
}
}
class Leaf implements Tree
{
{
_word = word;
}
{
int order = word.compareTo(_word);
if (order < 0) return new LeftTree(new Leaf(word), _word);
if (order > 0) return new RightTree(_word, new Leaf(word));
return this;
}
public boolean contains
(String word
) {
return word.compareTo(_word) == 0;
}
public int size()
{
return 1;
}
{
return "(" + _word + ")";
}
}
class LeftTree implements Tree
{
private final Tree _left;
public LeftTree
(Tree left,
String word
) {
_left = left;
_word = word;
}
{
int order = word.compareTo(_word);
if (order < 0) return new LeftTree(_left.add(word), _word);
if (order > 0) return new BinaryTree(_left, _word, new Leaf(word));
return this;
}
public boolean contains
(String word
) {
int order = word.compareTo(_word);
return (order == 0) || ((order < 0) && _left.contains(word));
}
public int size()
{
return 1 + _left.size();
}
{
return "(" + _left.toString() + " " + _word + ")";
}
}
class RightTree implements Tree
{
private final Tree _right;
public RightTree
(String word, Tree right
) {
_word = word;
_right = right;
}
{
int order = word.compareTo(_word);
if (order < 0) return new BinaryTree(new Leaf(word), _word, _right);
if (order > 0) return new RightTree(_word,_right.add(word));
return this;
}
public boolean contains
(String word
) {
int order = word.compareTo(_word);
return (order == 0) || ((order > 0) && _right.contains(word));
}
public int size()
{
return 1 + _right.size();
}
{
return "(" + _word + " " + _right.toString() + ")";
}
}
class BinaryTree implements Tree
{
private final Tree _left;
private final Tree _right;
public BinaryTree
(Tree left,
String word, Tree right
) {
_left = left;
_word = word;
_right = right;
}
{
int order = word.compareTo(_word);
if (order < 0) return new BinaryTree(_left.add(word), _word, _right);
if (order > 0) return new BinaryTree(_left, _word, _right.add(word));
return this;
}
public boolean contains
(String word
) {
int order = word.compareTo(_word);
return (order == 0) || ((order < 0) && _left.contains(word)) || ((order > 0) && _right.contains(word));
}
public int size()
{
return 1 + _left.size() + _right.size();
}
{
return "(" + _left.toString() + " " + _word + " " + _right.toString() + ")";
}
}