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


  • 0
    C

    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){
                    node.add(stack.pop());
         		} else {
                    stack.pop();
                    tree.add(node);
         		}
         	}
    		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;
    	}
    }

  • 0
    H

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


  • 0
    R

    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?


Log in to reply
 

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