Complete the code to declare the method that finds the kth smallest element in a BST.
public int kthSmallest(TreeNode root, int k) {
count = 0;
return [1];
}The method calls an inorder traversal helper to find the kth smallest element.
Complete the inorder traversal method to visit nodes in ascending order.
private int inorder(TreeNode node, int k) {
if (node == null) return -1;
int left = [1];
if (left != -1) return left;
count++;
if (count == k) return node.val;
return inorder(node.right, k);
}The inorder traversal first visits the left subtree to get nodes in ascending order.
Fix the error in the count variable declaration to track visited nodes.
private int count = [1];Count should start at 0 to count nodes visited during traversal.
Fill both blanks to complete the TreeNode class definition.
public class TreeNode { int [1]; TreeNode [2]; TreeNode left, right; TreeNode(int val) { this.val = val; } }
The TreeNode class has an integer value and a parent reference.
Fill all three blanks to complete the iterative inorder traversal to find kth smallest.
public int kthSmallestIterative(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.[1](current);
current = current.[2];
}
current = stack.[3]();
k--;
if (k == 0) return current.val;
current = current.right;
}
return -1;
}Use stack.push to add nodes, move left, and stack.pop to remove nodes during traversal.
