# Time Limit Exceeded

• I am using a level order traversal which is a variant of O(n) algorithm. However I am getting Time Limit Exceeded 104 / 108 test cases passed. Could anyone please point out what might be wrong/optimized?

``````class Solution {
public int widthOfBinaryTree(TreeNode root) {
if(root ==null){
return 0;
}

Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
queue.offer(new TreeNode(Integer.MAX_VALUE));
List<Integer> list = new ArrayList<Integer>();

int maxLevelCount = 0;
int nullLevelCount =0;

while(! queue.isEmpty()){
TreeNode node = queue.poll();

if(node==null){
nullLevelCount++;
queue.offer(null);
queue.offer(null);
}
else if(node.val == Integer.MAX_VALUE) {
if(nullLevelCount == list.size()){
break;
}

int leftIndex=0;
int rightIndex =0;
for(int i=0; i<list.size(); i++){
if(list.get(i)!=null){
leftIndex =i;
break;
}
}

for(int i=list.size()-1; i>=0; i--){
if(list.get(i)!=null){
rightIndex =i;
break;
}
}

int levelCount = rightIndex- leftIndex +1;

if(levelCount > maxLevelCount){
maxLevelCount = levelCount;
}

queue.offer(new TreeNode(Integer.MAX_VALUE));
list = new ArrayList<Integer>();
nullLevelCount = 0;
continue;
}
else {