Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print the root node's value first in preorder traversal.
DSA C++
void preorder(Node* root) {
if (root == nullptr) return;
std::cout << root->[1] << " ";
preorder(root->left);
preorder(root->right);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'val' or 'key' which may not exist in the Node structure.
Trying to print the pointer instead of the value.
✗ Incorrect
The root node's data is accessed by 'data' in this Node structure.
2fill in blank
mediumComplete the code to recursively traverse the left subtree in preorder.
DSA C++
void preorder(Node* root) {
if (root == nullptr) return;
std::cout << root->data << " ";
preorder(root->[1]);
preorder(root->right);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling preorder on 'right' before 'left'.
Using non-existent members like 'child' or 'next'.
✗ Incorrect
In preorder traversal, after the root, we visit the left subtree first, so we call preorder on 'left'.
3fill in blank
hardFix the error in the preorder traversal to correctly traverse the right subtree.
DSA C++
void preorder(Node* root) {
if (root == nullptr) return;
std::cout << root->data << " ";
preorder(root->left);
preorder(root->[1]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling preorder on 'left' twice.
Using invalid member names like 'child' or 'next'.
✗ Incorrect
After visiting the left subtree, preorder traversal visits the right subtree, so we call preorder on 'right'.
4fill in blank
hardFill both blanks to complete the preorder traversal function that prints nodes in Root-Left-Right order.
DSA C++
void preorder(Node* root) {
if (root == nullptr) return;
std::cout << root->[1] << " ";
preorder(root->[2]);
preorder(root->right);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping 'left' and 'right' in traversal order.
Using 'val' instead of 'data' for the node's value.
✗ Incorrect
We print the root's 'data' first, then recursively traverse the 'left' subtree before the right.
5fill in blank
hardFill all three blanks to complete the preorder traversal that prints root, left subtree, then right subtree.
DSA C++
void preorder(Node* root) {
if (root == nullptr) return;
std::cout << root->[1] << " ";
preorder(root->[2]);
preorder(root->[3]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of left and right traversal.
Using 'val' instead of 'data' for the node's value.
✗ Incorrect
Print the root's 'data', then recursively traverse 'left' subtree, then 'right' subtree.