Java Solution with Queue, using the queue's size to label the nodes' number in each level.


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

    }


Log in to reply
 

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