Given the root of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation.
It is guaranteed that the answer will in the range of 32-bit signed integer.
I am trying to solve this Binary Tree problem. I am using an approach which uses flat maps and which seems conceptually correct by running via the terminal on the first test case. However, pasting the code inside Leetcode gives “Time Limit Exceeded” error. Here is my implementation.
var widthOfBinaryTree = function(root) {
if ([undefined, null].includes(root)) {
return 0
}
let frontierRef = [root]
result = 1
while (frontierRef[0] !== undefined) { //Empty or not
let newElements = frontierRef.flatMap(function (node) {
if (node) {
return [node.left, node.right]
} else {
return [null, null]
}
})
let lastNonNullPos = 0;
//Find the first non-null element
for (let i = newElements.length - 1; i > -1; i--) {
if (newElements[i]) {
lastNonNullPos = i;
break;
}
}
//Get all the nodes from the first till the last non-null node, inclusive
newElements = newElements.slice(0, lastNonNullPos + 1);
result = Math.max(newElements.length, result)
frontierRef = newElements;
}
return result
};
I would like to ask if anyone knows what could be the slow operation and how to optimize it to make it runnable. Let me know if more information is required to solve the problem.