I've got a TreeNode class that represents a node in the tree and a LinkedTree class. In this one I want to get a list with every ancestor of a node. In every node I save the value, the node of the parent and a list with all the children. Therefore I should be able to get a list of the ancestors with the parent in the node, the parent of this node and so on.
I tried it recursive. Here are two versions of my code:
Version 1:
public List<Position<E>> ancestors(Position<E> p) throws
InvalidPositionException {
if(invalidPosition(p)) {
throw new InvalidPositionException("Position is not in the current
tree");
}
List<Position<E>> ancestors = new ArrayList<>();
if(!isRoot(p)) {
ancestors.add(((TreeNode<E>) p).getParent());
ancestors(((TreeNode<E>) p).getParent());
}
return ancestors;
}
Version 2:
public List<Position<E>> ancestors(Position<E> p) throws
InvalidPositionException {
List<Position<E>> ancestors = new ArrayList<>();
if(isRoot(p)) {
return ancestors;
}
for(Position<E> e : positions()) {
ancestors.add(((TreeNode<E>) e).getParent());
if(e.equals(p)) {
ancestors(((TreeNode<E>) e).getParent());
}
}
return ancestors;
}