【发布时间】: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 就是这样一个例子。