【问题标题】:Traversing a tree that has an arraylist containing an arbitrary number of sub-trees as its children遍历具有数组列表的树,该数组列表包含任意数量的子树作为其子树
【发布时间】:2019-04-29 10:53:53
【问题描述】:

我正在做一些考试复习,在过去的试卷上发现了这个问题:

首先,有人会实现这样的树还是只是一个考试问题?

其次,我真的很困惑如何去做。我想使用 BFS 或 DFS,但它们只适用于二叉树,而且我对递归不是很好,所以在那里也遇到了困难。

我想出了这个可行的方法,但它真的很丑,不适用于一般情况,只有这棵特殊的树:

public ArrayList<Integer> getLeafValues() {
    ArrayList<Integer> leafList = new ArrayList<>();
    Tree current = this;
    for (Tree t : current.children) {
        if (t.children.isEmpty()) {
            leafList.add(t.data);
        } else {
            for (Tree t2 : t.children) {
                if (t2.children.isEmpty()) {
                    leafList.add(t2.data);
                } else {
                    for (Tree t3 : t2.children) {
                        if (t3.children.isEmpty()) {
                            leafList.add(t3.data);
                        }
                    }
                }
            }
        }
    }
    return leafList;
}  

正如我在考试修订前所说的那样,这方面的任何帮助都会很棒,而不是家庭作业。谢谢

【问题讨论】:

  • 考虑使用递归来解决这个问题。
  • I wanted to use BFS or DFS but they only work for binary trees 不,它们适用于任何树木。
  • 啊哦,我弄错了,谢谢@csehydrogen
  • 首先,有人会实现这样的树吗?或者它只是一个考试问题?当然,Trie 就是这样一个例子。

标签: java arraylist tree


【解决方案1】:

这样的问题可以用递归来解决:

public ArrayList<Integer> getLeafValues() {
    ArrayList<Integer> leafList = new ArrayList<>();
    getLeaves (this, leafList);
    return leafList;
}

public void getLeaves (Tree current, List<Integer> leafList)
{
    if (current.children.isEmpty()) {
        leafList.add(current.data);
    } else {
        for (Tree t : current.children) {
            getLeaves (t, leafList);
        }
    }
}

当你到达一个叶子(即没有孩子的树)时递归结束,在这种情况下你将该叶子添加到List

如果当前节点有子节点,则在所有子节点上递归调用该方法,以收集其子树的叶子。

【讨论】:

  • 非常感谢!我没有想到要实现一个 hepler 方法。
猜你喜欢
  • 1970-01-01
  • 2019-02-25
  • 1970-01-01
  • 2020-04-21
  • 2011-09-16
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多