@@ -0,0 +1,2189 @@
+/*%0A *Key point: using Queue to do BFS%0A * I use two queues to store nodes in current level and next level, %0A * after we process current level queue, simply swapping the reference%0A * of current and next level queue can largely simplify the code%0A *%0A * There is solution only need one queue that using two variables to %0A * indicate the number of nodes in current level and next level%0A */%0A%0A/**%0A * Definition for binary tree%0A * public class TreeNode %7B%0A *     int val;%0A *     TreeNode left;%0A *     TreeNode right;%0A *     TreeNode(int x) %7B val = x; %7D%0A * %7D%0A */%0Apublic class Solution %7B%0A    public ArrayList%3CArrayList%3CInteger%3E%3E levelOrder(TreeNode root) %7B%0A        ArrayList%3CArrayList%3CInteger%3E%3E result = new ArrayList%3CArrayList%3CInteger%3E%3E();%0A        %0A        if(root == null)%0A            return result;%0A        %0A        //init two queues%0A        Queue%3CTreeNode%3E tempQueue1 = new LinkedList%3CTreeNode%3E();%0A        Queue%3CTreeNode%3E tempQueue2 = new LinkedList%3CTreeNode%3E();%0A        %0A        Queue%3CTreeNode%3E helper = null;  //helper for swap the tempQueue1 and tempQueue2%0A        %0A        TreeNode currentNode = null;%0A        %0A        ArrayList%3CInteger%3E sameLevel = new ArrayList%3CInteger%3E();%0A        %0A        tempQueue1.add(root);%0A        %0A        //we can always concentrate on Queue1 because we'll swap them after process queue1%0A        while(tempQueue1.peek() != null)%7B%0A            currentNode = tempQueue1.poll();%0A            sameLevel.add(currentNode.val);%0A            %0A            if(currentNode.left != null)%0A                tempQueue2.add(currentNode.left);%0A            if(currentNode.right != null)%0A                tempQueue2.add(currentNode.right);%0A            %0A            //if the current level has been processed%0A            if(tempQueue1.peek() == null)%7B%0A                //add the current level to result%0A                result.add((ArrayList%3CInteger%3E)sameLevel.clone());  //clone() does shallow copy and return Object%0A                sameLevel.clear();%0A            %0A                //swap tempQueue1 and tempQueue2%0A                helper = tempQueue1;%0A                tempQueue1 = tempQueue2;%0A                tempQueue2 = helper;%0A            %7D%0A%0A        %7D%0A        %0A        return result;%0A    %7D%0A%7D

add question Binary Tree Level Order Traversal