Simple 2ms java solution using queue and arraylist<list<integer>>. no recursion


  • 0
    R
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> outputList = new ArrayList<List<Integer>>();
            Queue<TreeNode> queue = new LinkedList<>();
            if(root == null) return outputList;
            queue.add(root);
            
            while(queue.size() != 0) {
                int size = queue.size();
                List<Integer> tempList = new ArrayList<Integer>();
                for(int i = 0; i < size; i++) {
                    TreeNode node = queue.poll();
                    tempList.add(node.val);
                    if(node.left!= null) queue.add(node.left);
                    if(node.right!= null) queue.add(node.right);
                }
                outputList.add(0, tempList);
            }
            
            return outputList;
            
        }
    }
    

Log in to reply
 

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