如何在非二叉树中查找特定节点?
How to find a specific node in a non binary Tree?
我有一棵包含多个节点的树。每个节点都有一个父节点(或在根的情况下为null)、一个名称(name)和一个将子节点的名称映射到子节点对象的HashTable(children)。
给定节点的字符串名称,我想创建一个遍历树以查找特定节点并 return 的方法。如果该节点不存在,则 return null。
我认为递归方法是最好的。到目前为止我有这个:
public Node findNode(Node n, String s) {
if (n.name == s) {
return n;
} else {
for (Node child: n.children.values()) {
findNode(child, s);
}
}
}
我不确定将 null 语句放在哪里。
如果 child 有,那么 return 有。如果没有,那么 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;
}
这里是 Java 11+ 版本使用 Optional
搜索节点。
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();
}
我有一棵包含多个节点的树。每个节点都有一个父节点(或在根的情况下为null)、一个名称(name)和一个将子节点的名称映射到子节点对象的HashTable(children)。
给定节点的字符串名称,我想创建一个遍历树以查找特定节点并 return 的方法。如果该节点不存在,则 return null。
我认为递归方法是最好的。到目前为止我有这个:
public Node findNode(Node n, String s) {
if (n.name == s) {
return n;
} else {
for (Node child: n.children.values()) {
findNode(child, s);
}
}
}
我不确定将 null 语句放在哪里。
如果 child 有,那么 return 有。如果没有,那么 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;
}
这里是 Java 11+ 版本使用 Optional
搜索节点。
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();
}