Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a value into a Binary Search Tree (BST).
DSA C++
struct Node {
int data;
Node* left;
Node* right;
};
Node* insert(Node* root, int val) {
if (root == nullptr) {
root = new Node{val, nullptr, nullptr};
} else if (val [1] root->data) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' causes wrong placement in the tree.
Using '==' leads to incorrect logic for insertion.
✗ Incorrect
In a BST, values less than the current node go to the left subtree.
2fill in blank
mediumComplete the code to search for a value in a BST.
DSA C++
bool search(Node* root, int val) {
if (root == nullptr) return false;
if (root->data == val) return true;
if (val [1] root->data) {
return search(root->left, val);
} else {
return search(root->right, val);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' causes search in wrong subtree.
Using '==' in condition leads to redundant checks.
✗ Incorrect
To search in BST, go left if val is less than current node's data.
3fill in blank
hardFix the error in the code that finds the minimum value node in a BST.
DSA C++
Node* findMin(Node* root) {
while (root->[1] != nullptr) {
root = root->left;
}
return root;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'right' pointer leads to maximum value instead of minimum.
Using 'parent' or 'child' causes compilation errors.
✗ Incorrect
The minimum value in BST is found by going left until no more left child.
4fill in blank
hardFill both blanks to create a function that counts nodes in a BST.
DSA C++
int countNodes(Node* root) {
if (root == nullptr) return 0;
return 1 + countNodes(root->[1]) + countNodes(root->[2]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' or 'child' pointers which do not exist.
Counting only one subtree leads to incorrect total.
✗ Incorrect
Count nodes by adding 1 for current node plus counts of left and right subtrees.
5fill in blank
hardFill all three blanks to create a function that creates a map of node values to their depths in a BST.
DSA C++
void mapDepths(Node* root, int depth, std::map<int, int>& depthMap) {
if (root == nullptr) return;
depthMap[[1]] = [2];
mapDepths(root->[3], depth + 1, depthMap);
mapDepths(root->right, depth + 1, depthMap);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys or values in the map.
Not recursing on both left and right children.
✗ Incorrect
Map node's data to current depth, then recurse left and right subtrees.