2Brute2Best
🔥0
01

Level order (Tree BFS Sub-pattern)

Return the nodes grouped by level, sometimes in a twisted order (bottom-up, zigzag) or for a tree with many children per node.

Signals in the problem statement
  • ›

    "return the level order traversal"

  • ›

    "from left to right, level by level"

  • ›

    "zigzag" / "bottom-up level order"

What makes it different

Level Order Traversal is the template. Level Order II wants the deepest level first: run the same BFS and reverse the list of levels at the end (the values inside each level stay left to right). N-ary Level Order loops over children instead of left/right. Zigzag keeps the queue order normal and only changes where each value is written: index i on even levels, size − 1 − i on odd ones. Changing the push order of the children instead breaks the next level.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Binary Tree Level Order Traversal
    Basic Anchor·LeetCode #102
    Medium
  2. 2
    Binary Tree Level Order Traversal II
    Basic Reinforcement·LeetCode #107
    Medium
  3. 3
    N-ary Tree Level Order Traversal
    Slight Variation·LeetCode #429
    Medium
  4. 4Medium

Template

level-order-template.cpp
// Level order: snapshot the queue size, pop exactly that many → one level.
vector<vector<int>> levelOrder(TreeNode* root) {
    vector<vector<int>> levels;
    if (!root) return levels;
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()) {
        int size = q.size();                      // nodes on this level, fixed before we push children
        vector<int> level;
        for (int i = 0; i < size; i++) {
            TreeNode* node = q.front(); q.pop();
            level.push_back(node->val);
            if (node->left) q.push(node->left);   // children belong to the next round
            if (node->right) q.push(node->right);
        }
        levels.push_back(level);
    }
    return levels;
}
Remember this · Tree BFS
Trigger
Level order, per-level max/average, right side view, minimum depth, nodes at distance k.
Think
Does the question care about depth / rows rather than paths?
Key question
How many nodes are in the current level (queue size at the start of the level)?