以下是一个用Java构建树结构的示例程序:

import java.util.ArrayList;
import java.util.List;

public class TreeNode {
    private String name;
    private List<TreeNode> children;

    public TreeNode(String name) {
        this.name = name;
        this.children = new ArrayList<TreeNode>();
    }

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

    public String getName() {
        return name;
    }

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

    public static void main(String[] args) {
        TreeNode root = new TreeNode("root");
        TreeNode node1 = new TreeNode("node1");
        TreeNode node2 = new TreeNode("node2");
        TreeNode node3 = new TreeNode("node3");

        node1.addChild(new TreeNode("node1.1"));
        node1.addChild(new TreeNode("node1.2"));

        node2.addChild(new TreeNode("node2.1"));
        node2.addChild(new TreeNode("node2.2"));

        node3.addChild(new TreeNode("node3.1"));

        root.addChild(node1);
        root.addChild(node2);
        root.addChild(node3);

        System.out.println(root.getName());
        for (TreeNode child : root.getChildren()) {
            System.out.println("- " + child.getName());
            for (TreeNode grandchild : child.getChildren()) {
                System.out.println("  - " + grandchild.getName());
            }
        }
    }
}

在这个示例程序中,我们定义了一个TreeNode类来表示树节点。每个节点包含一个名称和一个子节点列表。我们可以使用addChild方法来向节点添加子节点。

main方法中,我们创建了一个根节点和三个子节点,并将它们添加到根节点中。我们还为每个节点添加了一些子节点。最后,我们遍历整个树结构并将节点名称打印到控制台上。

这个示例程序只是一个基本的树结构示例,您可以根据需要添加更多的节点和属性来构建更复杂的树结构。

用Java写一个构建树结构的程序

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

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