Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the maximum element in a BST by moving to the right child.
DSA C++
int findMax(Node* root) {
Node* current = root;
while (current->[1] != nullptr) {
current = current->right;
}
return current->data;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'left' instead of 'right' to traverse.
Trying to access a non-existent 'child' pointer.
✗ Incorrect
In a BST, the maximum element is found by moving to the right child until there is no right child left.
2fill in blank
mediumComplete the code to return -1 if the BST is empty before finding the maximum element.
DSA C++
int findMax(Node* root) {
if (root == [1]) {
return -1;
}
Node* current = root;
while (current->right != nullptr) {
current = current->right;
}
return current->data;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or false instead of nullptr.
Using NULL which is legacy in modern C++.
✗ Incorrect
To check if the tree is empty, compare root with nullptr in modern C++.
3fill in blank
hardFix the error in the loop condition to correctly traverse the BST to find the maximum element.
DSA C++
int findMax(Node* root) {
Node* current = root;
while (current->right [1] nullptr) {
current = current->right;
}
return current->data;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' which stops immediately if right is not nullptr.
Using comparison operators like '<=' or '>=' which are invalid for pointers.
✗ Incorrect
The loop should continue while current->right is not nullptr to move to the rightmost node.
4fill in blank
hardFill both blanks to complete the recursive function to find the maximum element in a BST.
DSA C++
int findMax(Node* root) {
if (root == nullptr) {
return -1;
}
if (root->right == [1]) {
return root->data;
}
return findMax(root->[2]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking left child instead of right child.
Returning root instead of root->data.
✗ Incorrect
If there is no right child (nullptr), current node is max; else recurse right.
5fill in blank
hardFill all three blanks to create a function that finds the maximum element iteratively and handles empty tree.
DSA C++
int findMax(Node* root) {
if (root == [1]) {
return -1;
}
Node* current = root;
while (current->[2] != [3]) {
current = current->right;
}
return current->data;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using left instead of right to traverse.
Using 0 or NULL instead of nullptr.
✗ Incorrect
Check if root is nullptr for empty tree, then move right while right child is not nullptr.