Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap the left and right child nodes of the root.
DSA C++
void mirror(Node* root) {
if (root == nullptr) return;
Node* temp = root->left;
root->left = root->[1];
root->right = temp;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning root->left to root->left again instead of root->right.
Swapping with a wrong pointer like parent or child.
✗ Incorrect
We swap the left child with the right child, so root->left should be assigned root->right.
2fill in blank
mediumComplete the code to recursively mirror the left subtree.
DSA C++
void mirror(Node* root) {
if (root == nullptr) return;
mirror(root->[1]);
mirror(root->right);
Node* temp = root->left;
root->left = root->right;
root->right = temp;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling mirror on root->right twice.
Calling mirror on an invalid pointer like parent.
✗ Incorrect
We need to recursively mirror the left subtree, so we call mirror on root->left.
3fill in blank
hardFix the error in the base case check to avoid null pointer dereference.
DSA C++
void mirror(Node* root) {
if (root == [1]) return;
mirror(root->left);
mirror(root->right);
Node* temp = root->left;
root->left = root->right;
root->right = temp;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using NULL which is legacy and less type-safe.
Using 0 or false which are not pointers.
✗ Incorrect
In modern C++, nullptr is the correct way to check for a null pointer.
4fill in blank
hardFill both blanks to complete the recursive mirror function correctly.
DSA C++
void mirror(Node* root) {
if (root == [1]) return;
mirror(root->[2]);
mirror(root->right);
Node* temp = root->left;
root->left = root->right;
root->right = temp;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong null check values.
Recursing on the wrong child pointer.
✗ Incorrect
The base case checks if root is nullptr, and then we recursively call mirror on root->left before swapping.
5fill in blank
hardFill all three blanks to implement the mirror function with both recursive calls and swapping.
DSA C++
void mirror(Node* root) {
if (root == [1]) return;
mirror(root->[2]);
mirror(root->[3]);
Node* temp = root->left;
root->left = root->right;
root->right = temp;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Missing one of the recursive calls.
Incorrect null check.
✗ Incorrect
Check for nullptr, then recursively mirror left and right subtrees before swapping children.