【发布时间】:2017-07-24 02:19:51
【问题描述】:
我有一棵节点树。
class Node {
String mName;
List<Node> children = new ArrayList<>();
Node(String name) {
mName = name;
}
}
我想检查所有的树节点,如果我找到一些 mName 为“Leonardo”的节点,我想将 Leonardo 的所有孩子添加到 Leonardo 的父亲并删除 Leonardo。
例如
初始树是:
Jessy
/ | \
Leonardo John Leonardo
/ \ / \ / \
Rafael David Leonardo Keren Denis Leonardo
|
Phillipe
结果应该是:
Jessy
/ | \
Rafael David John Denis Phillipe
|
Keren
(对Leonardo、Denis、Phillipe和Leonardo的子树结果的解释:Jessy的第三个儿子是Leonardo,因此Leonardo被移除,他的儿子(Denis和Leonardo)成为Jessy的儿子。但随后另一个莱昂纳多被免职,菲利普代替他来。)
孩子的顺序无关紧要(即,拉斐尔和大卫可以在菲利普之后)
假设当“Leonardo”在根中时,没有办法获得初始树。
我已经尝试过了,但不幸的是它不起作用..
for (int i = 0; i < root.children.size(); ++i) {
removeLeonardo(root, root.children.get(i));
}
public void removeLeonardo(Node curr, Node child) {
if (child == null || child.children.isEmpty() == true) {
return;
}
if (child.mName.equals("Leonardo") == true) {
// add all Leonardo's children to current father
for (int i = 0; i < child.children.size(); ++i) {
curr.children.add(child.children.get(i));
// apply the func for the current father with each of Leonardo's children
removeLeonardo(curr, child.children.get(i));
}
// remove "Leonardo" from the current father
curr.children.remove(child);
}
else { // no "Leonardo" found, so apply the func for each child and this child's children
for (int i = 0; i < child.children.size(); ++i) {
removeLeonardo(child, child.children.get(i));
}
}
}
但是 Java 不能通过引用来工作。你能帮我解决这个问题吗?
【问题讨论】:
标签: java algorithm recursion graph-algorithm breadth-first-search