I have implemented the LinkedBinaryTree structure and I want to make that tree cloneable, yet I couldn't figure out how to insert the Positions into the new tree properly.
Here is my Position interface:
public interface Position<E> extends Cloneable{
E getElement() throws IllegalStateException;
Position<E> clone() throws CloneNotSupportedException;
}
This is Node class and its clone method in LinkedBinaryTree class.(Node class also has setters and getters and other stuff. I didn't put them cause they are relevant to topic.).
protected static class Node<E> implements Position<E>, Cloneable {
public Position<E> clone(){
try {
return (Position<E>)super.clone();
}catch(CloneNotSupportedException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
These are the methods for traversal in AbstractBinaryTree class:
private void inorderSubtree(Position<E> p, List<Position<E>> snapshot) {
if (left(p) != null) {
inorderSubtree(left(p), snapshot);
}
snapshot.add(p);
if (right(p) != null) {
inorderSubtree(right(p), snapshot);
}
}
public Iterable<Position<E>> inorder() {
List<Position<E>> snapshot = new ArrayList<>();
if (!isEmpty())
inorderSubtree(root(), snapshot); // fill the snapshot recursively
return snapshot;
}
And this is the clone method of LinkedBinaryTree(I know it is not finished yet):
public LinkedBinaryTree<E> clone() throws CloneNotSupportedException{
LinkedBinaryTree<E> clonedTree = new LinkedBinaryTree<E>();
ArrayList<Position<E>> a = (ArrayList<Position<E>>) inorder();
Position<E> clonePosition = a.get(0).clone();
return clonedTree;
}
I can get the Positions with inorder method and clone every single Position but I don't know how to insert them into the new tree with the same order.