Convert hierarchical list to a flat list in java

前端 未结 4 569
悲哀的现实
悲哀的现实 2021-01-20 17:10

I have a hierarchical list like below and I want to convert it to a flat list.

I have wrote a method called convertToFlatList

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-20 18:01

    Actually this is the problem of level/recursive order traversal of a tree. Here is detail of the problem and solutions:

    https://en.wikipedia.org/wiki/Tree_traversal

    By the way, this is traversal (Depth first-Pre order) of your problem:

    static class Member {
      List children = new ArrayList<>();
      int id;
      boolean visit = false;
    }
    public List printList(Member member) {
      Stack stack =  new Stack<>();
      List list =  new ArrayList<>();
      stack.push(member);
      while(!stack.isEmpty()) {
        Member node = stack.pop();
        list.add(node);
        for(Member m: node.children) {
        stack.push(m);
        }
      }
      return list;
    }
    

提交回复
热议问题