-1

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;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Lisa
  • 11
  • 1

2 Answers2

0

For your version 1, you either need to pass the ancestors list along with the recursive call or add the returned list from the recursive call to the current one.

if(!isRoot(p)) {
    ancestors.add(((TreeNode<E>) p).getParent());

   //requires signature change and does not require a 'return' at the end of the method
    ancestors(((TreeNode<E>) p).getParent(), ancestors); 
}

Or

 if(!isRoot(p)) {
    ancestors.add(((TreeNode<E>) p).getParent());
   //Add the result of the recursive call to the current list
    ancestors.add(ancestors(((TreeNode<E>) p).getParent(), ancestors)); 
}
return ancestors;

It's difficult to comment on your second version without seeing the implementation of positions()

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
0

The return value of the ancestors() method is ignored; you need to use them.

May I suggest you pass a list to be appended instead, it would be more economical. This may involve an overloaded private version of the recursive method to avoid exposing this peculiar need for such list argument.

user2023577
  • 1,752
  • 1
  • 12
  • 23