0
0
DSA C++programming~10 mins

Zigzag Level Order Traversal in DSA C++ - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare the result vector for storing levels.

DSA C++
vector<vector<int>> [1];
Drag options to blanks, or click blank then click option'
Aresult
Blevels
Coutput
Dzigzag
Attempts:
3 left
💡 Hint
Common Mistakes
Using a single vector instead of vector>
Naming the variable something unrelated
2fill in blank
medium

Complete the code to check if the current level should be reversed.

DSA C++
if (level % 2 == [1]) { reverse(currentLevel.begin(), currentLevel.end()); }
Drag options to blanks, or click blank then click option'
A0
B1
C2
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Reversing even levels instead of odd
Using incorrect modulus value
3fill in blank
hard

Fix the error in the queue push operation for left and right children.

DSA C++
if (node->left) q.push([1]);
if (node->right) q.push([2]);
Drag options to blanks, or click blank then click option'
Anode->left
Bnode->right
Cleft
Dright
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing string literals instead of node pointers
Swapping left and right children
4fill in blank
hard

Fill both blanks to correctly iterate over the current level size and pop nodes.

DSA C++
int size = q.[1]();
for (int i = 0; i < size; i++) {
    TreeNode* node = q.[2]();
    q.pop();
    // process node
}
Drag options to blanks, or click blank then click option'
Asize
Bfront
Cback
Dempty
Attempts:
3 left
💡 Hint
Common Mistakes
Using back() instead of front()
Using empty() instead of size()
5fill in blank
hard

Fill all three blanks to complete the zigzag level order traversal function.

DSA C++
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    vector<vector<int>> [1];
    if (!root) return [2];
    queue<TreeNode*> q;
    q.push(root);
    int level = 0;
    while (!q.empty()) {
        int size = q.size();
        vector<int> currentLevel;
        for (int i = 0; i < size; i++) {
            TreeNode* node = q.front();
            q.pop();
            currentLevel.push_back(node->val);
            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }
        if (level % 2 == 1) {
            reverse(currentLevel.begin(), currentLevel.end());
        }
        [1].push_back(currentLevel);
        level++;
    }
    return [3];
}
Drag options to blanks, or click blank then click option'
Aresult
Blevels
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for declaration and return
Returning an uninitialized vector