102. Binary Tree Level Order Traversal

# Medium, BFS

BFS-宽度优先搜索遍历二叉树

  1. 2 Queues

  2. 1 Queue + Dummy node

  3. 1 Queue( best )

Solution 3: 1 Queue

Record size of each level, then do for-loop. Two inner loops.

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(root == null) return res;
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while( !queue.isEmpty() ) {
            List<Integer> level = new ArrayList<Integer>();
            int l = queue.size();
            while(l > 0) {
                root = queue.poll();
                if(root.left != null) queue.add(root.left);
                if(root.right != null) queue.add(root.right);
                l --;
                level.add(root.val);
            }
            res.add(level);
        }
        
        return res;
    }
}

Last updated