Simple Java Solution without recursion


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

Log in to reply
 

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