【问题标题】:How to get a list of all ancestors in a general java tree如何获取通用java树中所有祖先的列表
【发布时间】:2018-05-04 09:49:40
【问题描述】:

我有一个表示树中节点的 TreeNode 类和一个 LinkedTree 类。在这个我想得到一个节点的每个祖先的列表。在每个节点中,我保存值、父节点和包含所有子节点的列表。因此,我应该能够得到一个祖先列表,其中包含节点中的父节点、该节点的父节点等等。

我试过递归。这是我的代码的两个版本:

版本 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;
}

版本 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;
}

【问题讨论】:

  • 你没有提到这两个版本有什么问题。
  • 两个版本都不起作用...我只是尝试了不同的方法。我不知道该怎么做
  • 在 SO 中仅仅说不起作用并不是一个好问题。
  • 请添加positions()方法的代码

标签: java tree treenode ancestor


【解决方案1】:

对于您的版本 1,您需要将 ancestors 列表与递归调用一起传递,或者将递归调用返回的列表添加到当前列表。

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); 
}

或者

 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;

如果没有看到positions()的实现,很难评论你的第二个版本

【讨论】:

    【解决方案2】:

    祖先()方法的返回值被忽略;你需要使用它们。

    我建议您传递一个要附加的列表,这样会更经济。这可能涉及递归方法的重载私有版本,以避免暴露对此类列表参数的特殊需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 2020-11-14
      • 2011-07-23
      • 1970-01-01
      相关资源
      最近更新 更多