[Problem Statement][1]

Am trying to solve a Binary Tree problem and using an approach which uses flat maps and 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
 
 };




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.






 [1]: https://leetcode.com/problems/maximum-width-of-binary-tree/