其中chinaProvince是一个List集合,存放着中国所有的省份名称。

接下来,定义一个方法buildTree(),用于将countryMap中的数据转换为树形结构。该方法递归遍历countryMap中的每一个“国家”数据,将其作为根节点,然后遍历该国家所包含的“直辖市/省/州”数据,将它们作为该国家节点的子节点。最后返回根节点。

代码实现如下:

public class Tree { private Map<String, List> countryMap = new HashMap<String, List>();

public TreeNode buildTree() {
    TreeNode root = new TreeNode("Root");
    for (String country : countryMap.keySet()) {
        TreeNode countryNode = new TreeNode(country);
        List<String> provinceList = countryMap.get(country);
        for (String province : provinceList) {
            TreeNode provinceNode = new TreeNode(province);
            countryNode.addChild(provinceNode);
        }
        root.addChild(countryNode);
    }
    return root;
}

}

其中,TreeNode表示树节点,包含一个值属性和一个子节点集合,代码如下:

public class TreeNode { private String value; private List children;

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

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

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

public String getValue() {
    return value;
}

}

最后,调用buildTree()方法即可得到树形结构。

Tree tree = new Tree(); tree.countryMap.put("中国", chinaProvince); TreeNode root = tree.buildTree();

可以使用递归遍历树形结构,将节点值输出。

public void printTree(TreeNode node, int level) { String prefix = ""; for (int i = 0; i < level; i++) { prefix += " "; } System.out.println(prefix + node.getValue()); for (TreeNode child : node.getChildren()) { printTree(child, level + 1); } }

调用printTree()方法即可输出树形结构。

tree.printTree(root, 0)


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

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