Java accepted 7ms solution (using queue instead of stack)

  • 0

    The tag for this problem is using a stack, and I've looked at those solutions and found that they either push the current level list or an iterator. Here I just use a different thought: using dfs and queue(so that don't need to reverse).

    public class NestedIterator implements Iterator<Integer> {
        // i'd like to use dfs + stack, dfs for maintaining the order, and stack for storing the correct order
        //Stack <Integer> stack;
        Queue<Integer> queue;
        public NestedIterator(List<NestedInteger> nestedList) {
            queue = new LinkedList<Integer>();
            if (nestedList != null && nestedList.size() > 0) {
                dfs (queue, nestedList);
        private void dfs (Queue<Integer> queue, List<NestedInteger> list) {
            for (NestedInteger n : list) {
                if (n.isInteger()) {
                } else {
                    dfs(queue, n.getList());
        public Integer next() {
            return queue.poll();
        public boolean hasNext() {
            return !(queue.size() == 0);

Log in to reply

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