Java 2ms solution with queue and two counters,clear and easy


  • 0
    Z
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if(root == null){
                return result;
            }
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            int i = 1,j = 1; 
            while(!queue.isEmpty()){
                List<Integer> list = new ArrayList<Integer>();
                while(j!=0){
                    TreeNode node = queue.poll();
                    list.add(node.val);
                    i--;
                    j--;
                    if(node.left != null){
                        queue.add(node.left);
                        i++;
                    }
                    if(node.right != null){
                        queue.add(node.right);
                        i++;
                    }
                }
                j=i;
                result.add(0,list);
            }
            return result;
        }
    

Log in to reply
 

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