I have a helper function that iterates through a binary search tree breadth first, and inserts each 'level' of the binary tree into a subarray, which is then pushed into a 2d array.
For example:
// a
// / \
// b c
// / \ \
// d e f
Looks like this:
// [
// ['a'],
// ['b', 'c'],
// ['d', 'e', 'f']
// ]
Here is my helper function:
const myLevels = (root) => {
const subLevels = [];
const queue = [{
node: root,
currentLevel: 0,
}];
while (queue.length > 0) {
let { node, currentLevel } = queue.shift();
if (subLevels.length === currentLevel) {
subLevels.push([node.val]);
} else {
subLevels[currentLevel].push(node.val);
};
if (node.left !== null) queue.push({ node: node.left, currentLevel: currentLevel + 1 });
if (node.right !== null) queue.push({ node: node.right, currentLevel: currentLevel + 1 });
};
return subLevels;
};
This works, however, I want to use the helper function in another function which will return a specific element(s) out of each level that is returned by the helper function. For example, what if I wanted to return the leftmost and rightmost elements from each level? Or what if I wanted to find the second largest value in each level (assuming that each node value consists of a number), or what if I wanted to return the vowels from each level?
My current approach is to iterate through each sub-array of the 2d array, and then iterate through those elements, as this approach makes the most sense to me. However, I have no idea how to conceptualize keeping track of each level, and telling my function to 'look at this subarray like it's a brand new array'.
This is my main function thus far:
function findXEachLevel(root) {
const levels = myLevels(root);
let finalArray = [];
for (let i = 0; i < levels.length; i++) {
let currentLevel = levels[i];
console.log(currentLevel) // Shows the current subarray in the 2d array
for (let j = 0; j < currentLevel.length; j++) {
let currentValue = currentLevel[j];
console.log(currentValue) // Shows the current value in the subarray
};
};
};
Would a callback be a viable solution here, or is there a simpler approach?