Write an Iterator that takes a nested(deep) list and flattens it out. For e.g. Collection A = {1, 2, {3, 4, 5, {6, 7}, {8,9}}, 10} When you call
DeepIterator it = new DeepIterator(A) ;
while(it.hasNext()){
System.out.println(it.next);
}
The key part of this problem is that the processed data is Collection type, which is the rawest type. It can contain anything.
We can treat it as a tree. The problem will change to traverse the leaf node in tree. So traversal a tree’s leaf node is straight forward. We can use stack to do preorder traversal.
However, we notice that a Collection has Collection.iterator(). This helps a lot. We put Iterator in stack. For each node’s children, we only store an iterator. In this way, space complexity is the deep of the tree.
check my code on github: link
Pingback: Flatten Nested List Iterator | allenlipeng47()