




Sponsored
Sponsored
The recursive approach leverages the call stack to manage the traversal of the multi-dimensional array. This approach requires defining a function that will be called recursively whenever an array is encountered.
When implementing this recursively, we check if the element is an integer; if so, we yield it. If it is an array, we recursively call the function on this array.
Time Complexity: O(N), where N is the total number of integers in the arrays since we visit each element once. 
Space Complexity: O(D) in the worst case due to recursion, where D is the depth of the nested lists.
1def inorderTraversal(arr):
2
The function inorderTraversal takes a multi-dimensional array arr and iterates over its elements. If an element is an integer, it's directly yielded. If it is a list, the function is called recursively on the sublist, using yield from to yield each item from the resulting generator.
This method uses a stack to keep track of the state of the array traversal. It mimics the behavior of the call stack in recursion but uses an explicit data structure. We push elements onto the stack in reverse order, and pop them to yield integers or explore more sub-arrays.
Time Complexity: O(N), where N is the total number of integers in the arrays.
Space Complexity: O(N) due to the use of the stack.
1def inorderTraversal(arr):
2    stack = arr[::-1]
3    while stack:
4        item = stack.pop()
5        if isinstance(item, int):
6            yield item
7        elif isinstance(item, list):
8            stack.extend(reversed(item))
9
10# Usage example:
11arr = [[[6]], [1, 3], []]
12generator = inorderTraversal(arr)
13print(list(generator))The inorderTraversal function initializes a stack with the reversed main array. We pop elements from the stack; if it's an integer, we yield it. If it is a list, its elements are pushed onto the stack in reverse order to maintain the original order while traversing.