By Long Luo

Here are 2 approaches to solve this problem in Java, DFS and Iteration approach.

# DFS

We can store all the integers in an array, just traversing the array.

## Analysis

• Time Complexity:

• $\texttt{NestedIterator}$: $O(n)$.
• $\texttt{next()}$: $O(1)$
• $\texttt{hasNext()}$: $O(1)$
• Space Complexity: $O(n)$.

# Iteration (Using Stack)

We can use a Stack to maintain all nodes on the path from the root node to the current node.

The stack stores the iterators, which is a pointer to the element.

## Analysis

• Time Complexity:

• $\texttt{NestedIterator}$: $O(1)$.
• $\texttt{next()}$: $O(1)$
• $\texttt{hasNext()}$: $O(1)$
• Space Complexity: $O(n)$.

The Iteration approach is better.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗