I have a hierarchical list
like below and I want to convert it to a flat list
.
I have wrote a method called convertToFlatList
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;
}