import java.util.*;

public class LinkedSimpleTree implements SimpleTree {
    private Node root;
    private int size;

    public LinkedSimpleTree() {
        root = null;
        size = 0;
    }
    public LinkedSimpleTree(Object element) {
        root = new Node(element, null,  new Vector());
        size = 1;
    }

    private Node checkPosition(Position position) throws SimpleTreeException {
        try {
            return ((Node) position);
        } catch (ClassCastException e) {
            throw new SimpleTreeException("Invalid position.");
        }
    }

    public int size () {
        return size;
    }
    public boolean isEmpty() {
        return (size == 0);
    }

    public Position root() throws SimpleTreeException {
        if (isEmpty()) {
            throw new SimpleTreeException("Empty tree has no root.");
        }
        return root;
    }
    public Position parent(Position position) throws SimpleTreeException {
        if (isRoot(position)) {
            throw new SimpleTreeException("Root has no parent.");
        }
        Node node = checkPosition(position);
        return node.parent;
    }
    public Enumeration children(Position position) throws SimpleTreeException {
        Node node = checkPosition(position);
        return node.children.elements();
    }
    public boolean isInternal(Position position) throws SimpleTreeException {
        Node node = checkPosition(position);
        return children(node).hasMoreElements();
    }
    public boolean isExternal(Position position) throws SimpleTreeException {
        return (!isInternal(position));
    }
    public boolean isRoot(Position position) throws SimpleTreeException {
        Node node = checkPosition(position);
        return (node.parent == null);
    }

    public void addChild(LinkedSimpleTree tree) {
        root.children.addElement(tree.root);
        tree.root.parent = root;
        size += tree.size;
    }        
}
