Java 3 ms solution using queue and LinkedList addFirst


  • 1
    M
     public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();
        if(root == null){
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int queueLen = queue.size();
            List<Integer> curRowResult = new ArrayList<Integer>();
            for(int i = 0 ; i< queueLen; i++){
                TreeNode curElem = queue.poll();
                curRowResult.add(curElem.val);
                if(curElem.left != null){
                    queue.offer(curElem.left);
                }
                if(curElem.right != null){
                    queue.offer(curElem.right);
                }
            }
            result.addFirst(curRowResult);
        }
       
        return result;
    }

Log in to reply
 

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