Super Simple Java solution using a queue and DFS


  • 1
    S

    Using a queue to store all the elements by doing a DFS.

    public class NestedIterator implements Iterator<Integer> {

    Queue<Integer> q;
    
    public NestedIterator(List<NestedInteger> nestedList) {
        q = new LinkedList<Integer>();
        dfs_parent(nestedList);
    }
    
    public void dfs_parent(List<NestedInteger> nestedList){
    	for(NestedInteger ni : nestedList){
    		dfs(ni);
    	}
    }
    public void dfs(NestedInteger ni){
    	if(ni.isInteger()) {
    		q.offer(ni.getInteger());
    		return;
    	}
    	dfs_parent(ni.getList());
    }
    
    @Override
    public Integer next() {
        return q.poll();
    }
    
    @Override
    public boolean hasNext() {
        return !q.isEmpty();
    }
    

    }


Log in to reply
 

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