0
0
DSA C++programming~10 mins

Why BST Over Plain Binary Tree in DSA C++ - Test Your Knowledge

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A<
B>
C==
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' causes wrong placement in the tree.
Using '==' leads to incorrect logic for insertion.
2fill in blank
medium

Complete 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'
A>
B>=
C==
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' causes search in wrong subtree.
Using '==' in condition leads to redundant checks.
3fill in blank
hard

Fix 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'
Aleft
Bright
Cparent
Dchild
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'right' pointer leads to maximum value instead of minimum.
Using 'parent' or 'child' causes compilation errors.
4fill in blank
hard

Fill 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'
Aleft
Bright
Cparent
Dchild
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' or 'child' pointers which do not exist.
Counting only one subtree leads to incorrect total.
5fill in blank
hard

Fill 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'
Aroot->data
Bdepth
Cleft
Dright
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys or values in the map.
Not recursing on both left and right children.