Easy to understand Java solution BFS.


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

Log in to reply
 

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