-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnested_array_generator.js
More file actions
30 lines (25 loc) · 901 Bytes
/
Copy pathnested_array_generator.js
File metadata and controls
30 lines (25 loc) · 901 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var inorderTraversal = function*(arr) {
if(arr.length !== 0){
for(const item of arr){
if(Array.isArray(item)){
yield* inorderTraversal(item)
}else{
yield item;
}
}
}
};
// ................A more optimized version
var inorderTraversal = function* (arr) {
const stack = [...arr.reverse()];
while (stack.length > 0) {
const item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item.reverse());
} else {
yield item;
}
}
};
// Avoid Recursive Function Calls: Recursive function calls could lead to stack overflow for deeply nested arrays. Instead, we can implement the traversal iteratively using an explicit stack.
// Iterative Approach Using a Stack: This avoids recursion while preserving the same in-order traversal behavior.