Complete the code to declare the function that finds the kth smallest element in a BST.
int kthSmallest(TreeNode* root, int k) {
int count = 0;
int result = 0;
inorder(root, k, count, [1]);
return result;
}The inorder traversal function updates the result variable when the kth element is found.
Complete the inorder traversal code to find the kth smallest element.
void inorder(TreeNode* root, int k, int& count, int& result) {
if (!root) return;
inorder(root->left, k, count, result);
count++;
if (count == [1]) {
result = root->val;
return;
}
inorder(root->right, k, count, result);
}The traversal checks if the current count matches k to find the kth smallest element.
Fix the error in the base case of the inorder traversal function.
void inorder(TreeNode* root, int k, int& count, int& result) {
if (root == [1]) return;
inorder(root->left, k, count, result);
count++;
if (count == k) {
result = root->val;
return;
}
inorder(root->right, k, count, result);
}In modern C++, nullptr is the correct way to check for a null pointer.
Fill both blanks to complete the iterative inorder traversal to find the kth smallest element.
int kthSmallest(TreeNode* root, int k) {
std::stack<TreeNode*> stack;
TreeNode* current = root;
int count = 0;
while (current != [1] || !stack.[2]()) {
while (current != nullptr) {
stack.push(current);
current = current->left;
}
current = stack.top();
stack.pop();
count++;
if (count == k) return current->val;
current = current->right;
}
return -1;
}The loop continues while current is not nullptr or the stack is not empty.
Fill all three blanks to complete the recursive helper function signature and call.
void [1](TreeNode* root, int k, int& count, int& result) { if (root == nullptr) return; [1](root->left, k, count, result); count++; if (count == k) { result = root->val; return; } [1](root->right, k, count, result); } int kthSmallest(TreeNode* root, int k) { int count = 0; int result = 0; [2](root, k, count, result); return result; }
The helper function is named consistently as inorder in both definition and calls.