Complete the code to insert a value into a Binary Search Tree (BST).
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;
}In a BST, values less than the current node go to the left subtree.
Complete the code to search for a value in a BST.
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);
}
}To search in BST, go left if val is less than current node's data.
Fix the error in the code that finds the minimum value node in a BST.
Node* findMin(Node* root) {
while (root->[1] != nullptr) {
root = root->left;
}
return root;
}The minimum value in BST is found by going left until no more left child.
Fill both blanks to create a function that counts nodes in a BST.
int countNodes(Node* root) {
if (root == nullptr) return 0;
return 1 + countNodes(root->[1]) + countNodes(root->[2]);
}Count nodes by adding 1 for current node plus counts of left and right subtrees.
Fill all three blanks to create a function that creates a map of node values to their depths in a BST.
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);
}Map node's data to current depth, then recurse left and right subtrees.
