[英]How to find a specific node in a non binary Tree?
I have a tree that contains multiple nodes.我有一个包含多个节点的树。 Each node has a parent node (or null in the case of the root), a name (name), and a HashTable (children) that maps the name of the child node to the child node object.每个节点都有一个父节点(在根节点的情况下为 null)、一个名称(名称)和一个将子节点的名称映射到子节点对象的哈希表(子节点)。
Given the string name of the node, I want to create a method that iterates through the tree to find the specific node and return it.给定节点的字符串名称,我想创建一个方法来遍历树以查找特定节点并返回它。 If the node doesn't exist then return null.如果节点不存在,则返回 null。
I thought a recursive method would be best.我认为递归方法是最好的。 So far I have this:到目前为止,我有这个:
public Node findNode(Node n, String s) {
if (n.name == s) {
return n;
} else {
for (Node child: n.children.values()) {
findNode(child, s);
}
}
}
I'm not sure exactly where to put the null statement.我不确定将 null 语句放在哪里。
If a child has it, then return it.如果孩子有它,然后将其归还。 If not, then return null
.如果没有,则返回null
。
public Node findNode(Node n, String s) {
if (n.name == s) {
return n;
} else {
for (Node child: n.children.values()) {
Node result = findNode(child, s);
if (result != null) {
return result;
}
}
}
return null;
}
Here is Java 11+ version using Optional
to search for the node.这是使用Optional
搜索节点的 Java 11+ 版本。
public Optional<Node> search (Node node, String needle) {
if (node.getValue().equals(needle)) {
return Optional.of(node);
} else {
for (var child : node.getChildren()) {
var result = search(child, needle);
if (result.isPresent()) {
return result;
}
}
}
return Optional.empty();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.