import java.util.Random;
public class Main {
public static void main
(String[] args
) { BinaryTree tree = new BinaryTree();
for (int i = 0; i < 10; i++) {
tree.add(random.nextInt(10));
}
tree.dump();
}
}
class BinaryTree {
Node root = new EmptyNode();
void add(int value) {
this.root.add(new RootResult(this), value);
}
void dump() {
this.root.dump("");
}
}
interface Node {
void add(Result result, int value);
}
class EmptyNode implements Node {
@Override
public void add(Result result, int value) {
result.setResult(new ValueNode(value, this, this));
}
@Override
public void dump
(String space
) { }
}
class ValueNode implements Node {
int value;
Node left;
Node right;
ValueNode(int value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
@Override
public void add(Result result, int value) {
if (value < this.value) {
this.left.add(new LeftResult(this), value);
} else {
this.right.add(new RightResult(this), value);
}
}
@Override
public void dump
(String space
) { this.right.dump(space + " ");
System.
out.
println(space
+ this.
value); this.left.dump(space + " ");
}
}
interface Result {
void setResult(ValueNode valueNode);
}
class RootResult implements Result {
BinaryTree tree;
RootResult(BinaryTree tree) {
this.tree = tree;
}
@Override
public void setResult(ValueNode root) {
tree.root = root;
}
}
class LeftResult implements Result {
ValueNode node;
LeftResult(ValueNode node) {
this.node = node;
}
@Override
public void setResult(ValueNode left) {
node.left = left;
}
}
class RightResult implements Result {
ValueNode node;
RightResult(ValueNode node) {
this.node = node;
}
@Override
public void setResult(ValueNode right) {
node.right = right;
}
}