获取部门树(下),根据需要显示的层数去显示该部门树。

在实际开发中,在树结构中有可能绑定很多数据,例如部门名称、人数....

 

在需要显示部门结构时,不会直接把一整棵部门树展开显示,

一般会先显示根结点、再显示根结点下的子节点、再去子子节点、逐层显示;

又或者显示两层或者三层结构,先展示部分结构,再根据需要深入了解的结构前端再返回节点去访问该层下的数据。

 

import java.util.*;

public class getTree {
    static int[][] trees = {
    {-1, 1}, {-1, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}, {3, 7}, {3, 8}, {4, 9}, {4, 10}, {5, 11}, {5, 12}, {6, 13}};

    public static void main(String[] args) {
        System.out.println(tree(-1, 2l));
    }

    static List longList = new ArrayList<>();

    public static Map tree(Integer department_code, Long layer) {//layer为显示的层数
        Map tree = new HashMap();
        if (!longList.contains(department_code)) {
            longList.add(department_code);
            tree.put("node", department_code);
            List sub = new ArrayList<>();
            if (department_code != null) {
                for (int i = 0; i < trees.length; i++) {
                    if (trees[i][0] == department_code) {
                        sub.add(trees[i][1]);
                    }
                }
                if (layer - 1 > 0) {
                    List sub1 = new ArrayList<>();
                    if (sub != null) {
                        for (Integer i : sub) {
                            Map subtree1 = tree(i, layer - 1);
                            sub1.add(subtree1);
                        }
                    }
                    tree.put("child", sub1);
                }
            }
        }
        return tree;
    }
}

当层数为2时,输出{node=-1, child=[{node=1}, {node=2}]}

你可能感兴趣的:(项目遇到的问题总结,java,递归法,树结构)