/** * 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>> res=new ArrayList<List<Integer>>(); if(root==null) return res; Queue<TreeNode> q=new LinkedList<TreeNode>(); q.offer(root); int size=q.size(); int count=0; List<Integer> templist=new ArrayList<Integer>(); while(!q.isEmpty()) { TreeNode temp=q.poll(); if(temp.left!=null) q.offer(temp.left); if(temp.right!=null) q.offer(temp.right); count++; templist.add(temp.val); if(count==size) { size=q.size(); count=0; res.add(templist); templist=new ArrayList<Integer>(); } } List<List<Integer>> revres=new ArrayList<List<Integer>>(); for(int i=res.size()-1;i>=0;i--) revres.add(res.get(i)); return revres; } }