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.
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.
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.
If a child has it, then return it. If not, then return 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.
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.