Simple recursive Java solution only 6ms

  • 0

    First convert the nestedInteger list to list of integers and then iterate over this list of integers. Space complexity is O(n) as we store all the integers in a list.

    ''' public class NestedIterator implements Iterator<Integer> {

    private List<Integer> data;
    private Iterator<Integer> iterator;
    public NestedIterator(List<NestedInteger> nestedList) {
        data = new ArrayList<Integer>();
        iterator = data.iterator();
    private void addAllElements(List<NestedInteger> nestedList) {
        for(NestedInteger each: nestedList) {
            if(each.isInteger()) data.add(each.getInteger());
            else addAllElements(each.getList());
    public Integer next() {
    public boolean hasNext() {
        return iterator.hasNext();


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.