Complete the code to perform an inorder traversal that visits nodes in ascending order.
void InorderTraversal(TreeNode node) {
if (node == null) return;
InorderTraversal(node.[1]);
Console.WriteLine(node.val);
InorderTraversal(node.right);
}The inorder traversal visits the left subtree first, then the node, then the right subtree. So, we call InorderTraversal on node.left first.
Complete the code to count nodes visited during inorder traversal.
int count = 0; int KthSmallest(TreeNode node, int k) { if (node == null) return -1; int left = KthSmallest(node.left, k); if (left != -1) return left; count++; if (count == [1]) return node.val; return KthSmallest(node.right, k); }
We compare the count of visited nodes with k to find the kth smallest element.
Fix the error in the code to correctly return the kth smallest element or -1 if not found.
int count = 0; int KthSmallest(TreeNode node, int k) { if (node == null) return -1; int left = KthSmallest(node.left, k); if (left != -1) return left; count++; if (count == k) return node.[1]; return KthSmallest(node.right, k); }
The TreeNode property for the node's value is val. Using the correct property returns the node's value.
Fill both blanks to complete the code that populates a dictionary mapping each node's value to its depth in the BST.
var depthMap = new Dictionary<int, int>();
void MapDepth(TreeNode node, int depth) {
if (node == null) return;
depthMap[node.val] = [1];
MapDepth(node.left, depth [2] 1);
MapDepth(node.right, depth + 1);
}We assign the current depth to the node's value. We recurse on the left child with depth + 1, same as the right child.
Fill all three blanks to complete the code that returns the kth smallest element using an iterative inorder traversal.
int KthSmallestIterative(TreeNode root, int k) {
var stack = new Stack<TreeNode>();
var current = root;
int count = 0;
while (current != null || stack.Count > 0) {
while (current != null) {
stack.Push(current);
current = current.[1];
}
current = stack.Pop();
count++;
if (count == [2]) return current.[3];
current = current.right;
}
return -1;
}The iterative inorder traversal goes left as far as possible, so current = current.left. We compare count with k to find the kth smallest, and return current.val.
