Java easiest BFS solution using queue


  • 2
    public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> list=new ArrayList<>();
            if(root==null) return list;
            Queue<TreeNode> q=new LinkedList<>();
            q.offer(root);
            while(!q.isEmpty()){
                List<Integer> temp=new ArrayList<>();
                int size=q.size();
                for(int i=0;i<size;i++){
                    TreeNode node=q.poll();
                    temp.add(node.val);
                    if(node.left!=null) q.offer(node.left);
                    if(node.right!=null) q.offer(node.right);
                }
                list.add(temp);
            }
            return list;
        }
    

Log in to reply
 

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