Sharing my clean Java solution


  • 0
    P

    Instead of using a nested loop to iterate over nodes of a level, we can add null in the queue to indicate the end of a level. This eliminates the need for the inner for loop.

     public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if(root == null)
                return result;
            
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            queue.add(null);
            List<Integer> current = new ArrayList<Integer>();
            TreeNode node = null;
            while(!queue.isEmpty()){
                node = queue.remove();
                if(node != null){
                    current.add(node.val);
                    if(node.left != null) queue.add(node.left);
                    if(node.right !=null) queue.add(node.right);
                }else{
                    //Create a copy of the current list and add to result
                    result.add(new ArrayList<Integer>(current));
                    current.clear();
                    if(!queue.isEmpty())
                        queue.add(null);
                }
            }
            
            return result;
        }
    

Log in to reply
 

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