This class should be generalized to allow trees with any type of value to be used. Add a type parameter E to the PreOrderList and TreeNode classes. Your getPreOrderList and preOrder method should be erased entirely; that should be implemented inside the TreeNode class. In fact, there is no need for the PreOrderList class at all; all that behavior could be implemented inside TreeNode:
public class TreeNode<E>{
public static TreeNode<E> fromIterator(Iterator<E> it){
if(!it.hasNext()) return null;
TreeNode<E> root = new TreeNode<E>();
forwhile(E e: listit.hasNext(){)
root.add(it.next());
}
public static TreeNode<E> fromIterable(Iterable<E> iterable){
return fromIterator(iterable.iterator());
}
public static TreeNode<E> fromArray(E ... array){
return fromIterable(Arrays.asList(array));
}
TreeNode<E> [] children;
E item;
private TreeNode(E item, TreeNode ... children) {
this.children = children;
this.item = item;
}
int childIdx;
public void add(E item){
if(children[childIdx] == null)
children[childIdx] = new TreeNode(item, new TreeNode[children.length]);
else children[childIdx].add(item);
childIdx++;
}
public boolean contains(Object item){
if (item==null?this.item==null:item.equals(this.item)) return true;
for(TreeNode<?> child: children)
if(child.contains(item)) return true;
return false;
}
@Override
public String toString(){
return String.format("%s(%s,%s)",item,left,right);
}
}