1 public class Solution { 2 public List<List<Integer>> levelOrder(TreeNode root) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 if(root == null) return res; 5 Queue<TreeNode> q = new LinkedList<TreeNode>(); 6 q.add(root); 7 int level = 0; 8 while(! q.isEmpty()) { 9 res.add(new ArrayList<Integer>()); // Important or res does not have space to hold data 10 int curSize = q.size(); 11 for(int i = 0; i < curSize; i++) { // remove all nodes in this level 12 TreeNode temp = q.remove(); 13 res.get(level).add(temp.val); 14 if(temp.left != null) q.add(temp.left); 15 if(temp.right != null) q.add(temp.right); 16 } 17 level++; 18 } 19 return res; 20 } 21 }
Traversal II:
public class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> ans = new ArrayList<List<Integer>>(); // IMPORTANT: change the second ArrayList to List. if (root == null) return ans; LinkedList<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); while (! q.isEmpty()) { ans.add(0, new ArrayList<Integer>()); int curSize = q.size(); for (int i = 0; i < curSize; i ++) { TreeNode node = q.remove(); ans.get(0).add(node.val); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); } } return ans; } }