I am trying to write a class that implements a tree using an array and I need some help to write an Iterator method that which returns an iterator of the elements stored in the tree. Here is my code.
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ArrayTree<E> implements Tree<E>{
protected ArrayTreeNode<E>[] tree;
protected E element;
public static final int CAPACITY = 1024;
protected List<ArrayTreeNode<E>> children;
protected ArrayTreeNode<E> parent;
protected ArrayTreeNode<E> root;
public ArrayTree()
{
tree = (ArrayTreeNode<E>[]) new Object[CAPACITY];
root = tree[0];
children = null;
element = null;
parent = null;
}
public ArrayTree(E e, int size)
{
tree = (ArrayTreeNode<E>[]) new Object[size];
element = e;
root = tree[0];
root.setElement(e);
children = null;
parent = null;
}
public void delete(E node) throws RootNonDeletableException
{
tree[Arrays.asList(tree).indexOf(node)] = null;
parent(tree[Arrays.asList(tree).indexOf(node)]).addChild(tree[Arrays.asList(tree).indexOf(node)],Arrays.asList(tree).indexOf(node));
}
public boolean isEmpty()
{
if (tree[0] == null)
return true;
else
return false;
}
public Iterator<E> iterator()
{
}
public E replace(E oldE, E newE)
{
tree[Arrays.asList(tree).indexOf(oldE)] = (ArrayTreeNode<E>) newE;
return newE;
}
public E root() throws EmptyTreeException
{
if (isEmpty())
throw new EmptyTreeException();
else
return (E) tree[0];
}
public int size()
{
int count = 0;
for (int i = 0; i < tree.length; i++)
count = count+1;
return count;
}
public Iterable<E> children(E node)
{
return (Iterable<E>) children;
}
public ArrayTreeNode<E> parent(ArrayTreeNode<E> node)
{
return parent;
}
public E parent(E node)
{
return (E) parent;
}
}
-
import java.util.ArrayList;
import java.util.List;
public class ArrayTreeNode<E> {
protected E element;
protected List<ArrayTreeNode<E>> children;
protected ArrayTreeNode<E> parent;
protected ArrayTreeNode<E> root;
public ArrayTreeNode()
{
this.setElement(null);
children = new ArrayList<ArrayTreeNode<E>>();
parent = root;
}
public ArrayTreeNode(E e)
{
parent = root;
children = new ArrayList<ArrayTreeNode<E>>();
element = e;
this.setElement(e);
}
public void setElement(E e)
{
element = e;
}
public void setChildren(List<ArrayTreeNode<E>> kids)
{
children = kids;
}
public void addChild(ArrayTreeNode<E> child, int i)
{
children.add(i, child);
}
}