107. Binary Tree Level Order Traversal II
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List> levelOrderBottom(TreeNode root) { if (root == null) return new LinkedList(); List<List> out = new ArrayList(); Queue q = new LinkedList(); q.offer(root); while(!q.isEmpty()){ ArrayList current = new ArrayList(); int size = q.size();//we must put it in variable is the size changes each loop for(int i =0; i < size; i++){ TreeNode c = q.poll(); if(c != null){ current.add(c.val); if(c.left != null) q.offer(c.left); if(c.right != null) q.offer(c.right); } } out.add(current); } Collections.reverse(out); return out; } }