Java 树查询实现示例 - 查找节点和路径
以下是一个简单的 Java 实现树查询的示例:
public class TreeNode {
private String data;
private List<TreeNode> children;
public TreeNode(String data) {
this.data = data;
this.children = new ArrayList<>();
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
public void addChild(TreeNode child) {
children.add(child);
}
public TreeNode findNode(String data) {
if (this.data.equals(data)) {
return this;
}
for (TreeNode child : children) {
TreeNode node = child.findNode(data);
if (node != null) {
return node;
}
}
return null;
}
public List<String> findPath(String data) {
List<String> path = new ArrayList<>();
if (this.data.equals(data)) {
path.add(this.data);
return path;
}
for (TreeNode child : children) {
List<String> childPath = child.findPath(data);
if (childPath != null) {
path.add(this.data);
path.addAll(childPath);
return path;
}
}
return null;
}
}
在这个示例中,我们创建了一个 TreeNode 类来表示树节点。每个节点包含一个数据项和子节点列表。我们还实现了两个方法来查找节点和路径。findNode 方法接受一个节点数据项,返回包含该数据项的节点。findPath 方法接受一个节点数据项,返回从根节点到包含该数据项的节点的路径。
这是一个简单的示例,可以根据需要进行扩展和修改。
原文地址: https://www.cveoy.top/t/topic/mskE 著作权归作者所有。请勿转载和采集!