java 递归

1)创建城市类和树状结构城市类

//城市类
class City {
    private int id;
    private String name;
    private int upperid;

    public City(int id, String name, int upperid) {
        this.id = id;
        this.name = name;
        this.upperid = upperid;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getUpperId() {
        return upperid;
    }


    public void setId(int _id) {
        this.id = _id;
    }

    public void setName(String _name) {
        this.name = _name;
    }

    public void setUpperId(int _upperid) {
        this.upperid = _upperid;
    }
}
//树状结构城市类
class TreeNode extends City {
    private List children = new ArrayList();

    public List getChildren() {
        return children;
    }

    public void setChildren(List _children) {
        this.children = _children;
    }

    public TreeNode(int id, String name, int upperid) {
        super(id, name,upperid);
    }
}

2)初始化数据,创建将列表集合转化成树集合

// 获取城市列表
private List GetList() {
    List list = new ArrayList<>();
    list.add(new City(1, "浙江", 0));
    list.add(new City(2, "江苏", 0));
    list.add(new City(3, "福建", 0));
    list.add(new City(11, "杭州", 1));
    list.add(new City(12, "嘉兴", 1));
    list.add(new City(21, "苏州", 2));
    list.add(new City(22, "无锡", 2));
    list.add(new City(31, "福州", 3));
    list.add(new City(32, "厦门", 3));
    list.add(new City(111, "萧山", 11));
    list.add(new City(112, "临安", 11));
    list.add(new City(121, "嘉善", 12));
    list.add(new City(122, "桐乡", 12));
    list.add(new City(211, "吴江", 21));
    list.add(new City(212, "常熟", 21));
    return list;
}

// 根据城市列表,递归获取城市树
private List GetTree(List list) {
    List tree = new ArrayList<>();
    for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
        City item = (City) iterator.next();
        // 获取根城市
        if (item.getUpperId() == 0) {
            TreeNode treeNode = new TreeNode(
                    item.getId()
                    , item.getName()
                    , item.getUpperId()
            );
            List myChildren = GetChildren(treeNode.getId(), list);
            treeNode.setChildren(myChildren);
            tree.add(treeNode);
        }
    }
    return tree;
}

private List GetChildren(int upperid, List list) {
    List children = new ArrayList<>();
    for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
        City item = (City) iterator.next();
        if (item.getUpperId() == upperid) {
            TreeNode child = new TreeNode(
                    item.getId(),
                    item.getName(),
                    item.getUpperId()
            );
            List myChildren = GetChildren(item.getId(), list);
            child.setChildren(myChildren);
            children.add(child);
        }
    }
    return children;
}

3)调用

List list=GetList();
List tree = GetTree(list);

你可能感兴趣的:(java,java,开发语言,递归)