Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a single vector instead of vector>
Naming the variable something unrelated
✗ Incorrect
The vector named 'result' is commonly used to store the final zigzag level order traversal.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Reversing even levels instead of odd
Using incorrect modulus value
✗ Incorrect
Odd levels (level % 2 == 1) are reversed to achieve zigzag order.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing string literals instead of node pointers
Swapping left and right children
✗ Incorrect
We must push the actual child nodes 'node->left' and 'node->right' into the queue.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using back() instead of front()
Using empty() instead of size()
✗ Incorrect
Use q.size() to get current level size and q.front() to access the first node in the queue.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for declaration and return
Returning an uninitialized vector
✗ Incorrect
The vector 'result' is declared, returned, and used to store levels.