# Binary Tree Level Order Traversal II - Time Limit Exceeded - How to improve the speed of my solution?

• Hi,

How can I improve the speed of the code below?

I am getting Submission Result: Time Limit Exceeded and I don't know where I could make it faster.

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();
Stack<Integer> stack = new Stack<Integer>();
ArrayList<Integer> node = new ArrayList<Integer>();

this.iterateAll(root, stack);

while(!stack.empty()){
if(stack.peek() != null){
} else {
stack.pop();
}
}
return tree;
}

public Stack<Integer> iterateAll(TreeNode root, Stack<Integer> stack){
if(root != null){
stack.push(root.val);
if(root.right != null){
iterateAll(root.right, stack);
}else{
stack.push(null);
}

if(root.left != null){
iterateAll(root.left, stack);
}else{
stack.push(null);
}
}
return stack;
}
}

• may be you have infinite loop, i just have the same question.....
you can try to debug in the local environment

• Maybe I think top-down level order, with recoding each level to a vector, and then reverse the vector would be quick and elegant, how about other leetcoders' opinions?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.