Java 7ms solution use queue

  • 0

    use flatNest() method to flat the nest recursively

    public class NestedIterator implements Iterator<Integer> {
    	Queue<Integer> queue;
    	public NestedIterator(List<NestedInteger> nestedList) {
    		queue = new LinkedList<Integer>();
    	public Integer next() {
    		return queue.poll();
    	public boolean hasNext() {
    		return !queue.isEmpty();
    	private void flatNest(List<NestedInteger> nestedList) {
    		for (NestedInteger i : nestedList) {
    			if (i.isInteger()) queue.offer(i.getInteger());
    			else flatNest(i.getList());

Log in to reply

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