以下是一个示例代码,用于遍历组织树并统计每个节点及其子节点中特定类型的数量:

public class OrganizationTree {

    private Node root;

    public OrganizationTree(Node root) {
        this.root = root;
    }

    public void traverseAndCount(String type) {
        traverseAndCount(root, type);
    }

    private int traverseAndCount(Node node, String type) {
        int count = 0;
        if (node.getType().equals(type)) {
            count++;
        }
        for (Node child : node.getChildren()) {
            count += traverseAndCount(child, type);
        }
        node.setCount(type, count);
        return count;
    }

}

public class Node {

    private String type;
    private int count;
    private List<Node> children;

    public Node(String type) {
        this.type = type;
        this.count = 0;
        this.children = new ArrayList<>();
    }

    public String getType() {
        return type;
    }

    public int getCount() {
        return count;
    }

    public void setCount(String type, int count) {
        if (this.type.equals(type)) {
            this.count = count;
        }
    }

    public List<Node> getChildren() {
        return children;
    }

    public void addChild(Node child) {
        children.add(child);
    }

}

// 使用示例
Node root = new Node('A');
Node b = new Node('B');
Node c = new Node('C');
Node d = new Node('D');
Node e = new Node('E');
Node f = new Node('F');
root.addChild(b);
root.addChild(c);
b.addChild(d);
b.addChild(e);
c.addChild(f);

OrganizationTree tree = new OrganizationTree(root);
tree.traverseAndCount('B');
System.out.println('Count of B in root: ' + root.getCount('B')); // 输出 2
System.out.println('Count of B in node B: ' + b.getCount('B')); // 输出 1

该代码首先定义了 OrganizationTree 类,其中包含 root 节点和 traverseAndCount 方法。traverseAndCount 方法通过递归遍历组织树,并统计每个节点及其子节点中特定类型的数量。Node 类包含节点类型、计数和子节点列表。

在使用示例中,我们创建了一个组织树,并调用 traverseAndCount 方法统计 B 类型的节点数量。最后,我们打印了根节点和 B 节点的计数。

此代码示例展示了如何使用 Java 代码遍历组织树结构,并根据特定类型进行统计。您可以根据实际需求修改代码,例如添加其他类型的统计或更复杂的逻辑。

Java 组织树遍历统计节点类型数量

原文地址: https://www.cveoy.top/t/topic/nmfi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录