用java递归查询一个组织机构树
时间: 2024-01-21 22:16:18 浏览: 106
假设组织机构树的节点结构如下:
```java
class OrgNode {
private String name; // 节点名称
private List<OrgNode> children; // 子节点列表
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<OrgNode> getChildren() {
return children;
}
public void setChildren(List<OrgNode> children) {
this.children = children;
}
}
```
递归查询组织机构树的代码如下:
```java
public class OrgTreeSearcher {
/**
* 递归查询组织机构树中指定名称的节点
* @param rootNode 组织机构树的根节点
* @param name 要查询的节点名称
* @return 查询到的节点,如果未查询到则返回null
*/
public OrgNode searchByName(OrgNode rootNode, String name) {
if (rootNode == null) {
return null;
}
if (rootNode.getName().equals(name)) {
return rootNode;
}
List<OrgNode> children = rootNode.getChildren();
if (children != null) {
for (OrgNode child : children) {
OrgNode result = searchByName(child, name);
if (result != null) {
return result;
}
}
}
return null;
}
}
```
使用示例:
```java
public static void main(String[] args) {
OrgNode root = new OrgNode();
root.setName("总公司");
OrgNode sub1 = new OrgNode();
sub1.setName("分公司1");
root.setChildren(Arrays.asList(sub1));
OrgNode sub11 = new OrgNode();
sub11.setName("子公司1-1");
sub1.setChildren(Arrays.asList(sub11));
OrgNode sub12 = new OrgNode();
sub12.setName("子公司1-2");
sub1.setChildren(Arrays.asList(sub12));
OrgNode sub121 = new OrgNode();
sub121.setName("子公司1-2-1");
sub12.setChildren(Arrays.asList(sub121));
OrgTreeSearcher searcher = new OrgTreeSearcher();
OrgNode result = searcher.searchByName(root, "子公司1-2-1");
System.out.println(result.getName()); // 输出:子公司1-2-1
}
```
阅读全文