Bird
Raised Fist0
DSA C#programming~10 mins

Kth Smallest Element in BST in DSA C# - Execution Trace

Choose your learning style10 modes available
Concept Flow - Kth Smallest Element in BST
Start at root node
↓
Traverse left subtree
↓
Visit current node
↓
Count visited nodes
↓
Is count == k?
No→Traverse right subtree
Yes↓
Return current node value
Traverse the BST in order (left, node, right), count nodes visited, return the kth visited node's value.
Execution Sample
DSA C#
int count = 0;
int result = -1;
void Inorder(TreeNode node, int k) {
  if (node == null) return;
  Inorder(node.left, k);
  count++;
  if (count == k) { result = node.val; return; }
  Inorder(node.right, k);
}
This code does an in-order traversal of the BST and finds the kth smallest element by counting nodes visited.
Execution Table
StepOperationNode VisitedCountPointer ChangesVisual State
1Start at root50Current = 55 / \ 3 7 / \ 2 4 8
2Traverse left subtree30Current = 35 / \ 3 7 / \ 2 4 8
3Traverse left subtree20Current = 25 / \ 3 7 / \ 2 4 8
4Visit node21Count=15 / \ 3 7 / \ 2 4 8
5Traverse right subtreenull1Current = null5 / \ 3 7 / \ 2 4 8
6Back to node31Current = 35 / \ 3 7 / \ 2 4 8
7Visit node32Count=25 / \ 3 7 / \ 2 4 8
8Traverse right subtree42Current = 45 / \ 3 7 / \ 2 4 8
9Visit node43Count=35 / \ 3 7 / \ 2 4 8
10Traverse right subtreenull3Current = null5 / \ 3 7 / \ 2 4 8
11Back to node53Current = 55 / \ 3 7 / \ 2 4 8
12Visit node54Count=45 / \ 3 7 / \ 2 4 8
13Traverse right subtree74Current = 75 / \ 3 7 / \ 2 4 8
14Traverse left subtreenull4Current = null5 / \ 3 7 / \ 2 4 8
15Back to node74Current = 75 / \ 3 7 / \ 2 4 8
16Visit node75Count=55 / \ 3 7 / \ 2 4 8
17Traverse right subtree85Current = 85 / \ 3 7 / \ 2 4 8
18Visit node86Count=65 / \ 3 7 / \ 2 4 8
19Traverse right subtreenull6Current = null5 / \ 3 7 / \ 2 4 8
20End traversalnull6Traversal complete5 / \ 3 7 / \ 2 4 8
💡 Traversal ends after visiting all nodes or when count reaches k.
Variable Tracker
VariableStartAfter Step 4After Step 7After Step 9After Step 12After Step 16After Step 18Final
count01234566
result-12345788
current node5234578null
Key Moments - 3 Insights
Why do we increment count only when visiting a node, not when traversing?
Because count tracks how many nodes have been visited in order. See execution_table rows 4,7,9 where count increments only on visiting nodes.
Why do we return the result immediately when count == k?
To stop unnecessary traversal once the kth smallest is found. In the table, after step 12 (count=4) if k=4, we would return result=5 immediately.
Why do we traverse left subtree first in BST?
Because in-order traversal visits nodes in ascending order: left subtree, node, right subtree. This ensures kth smallest is found by counting visits.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the count value after visiting node 3?
A1
B2
C3
D4
💡 Hint
Check execution_table row 7 where node 3 is visited and count is updated.
At which step does the traversal visit the kth smallest node if k=4?
AStep 12
BStep 9
CStep 16
DStep 18
💡 Hint
Look at execution_table where count reaches 4, which is step 12 visiting node 5.
If k=2, what would be the result after traversal?
A2
B4
C3
D5
💡 Hint
Refer to variable_tracker count and result after step 7 where count=2 and result=3.
Concept Snapshot
Kth Smallest Element in BST:
- Use in-order traversal (left, node, right)
- Keep count of visited nodes
- When count == k, return node value
- Stops traversal early once kth element found
- BST property ensures ascending order visit
Full Transcript
To find the kth smallest element in a Binary Search Tree (BST), we do an in-order traversal. This means we visit the left subtree first, then the current node, then the right subtree. We keep a count of how many nodes we have visited. When the count reaches k, we record the current node's value as the result and stop traversal. This works because in-order traversal visits nodes in ascending order in a BST. The execution table shows each step visiting nodes and updating count. The variable tracker shows how count and result change. Key moments clarify why count increments only on visiting nodes and why traversal order matters. The visual quiz tests understanding of count values and when the kth node is visited.

Practice

(1/5)
1. What does the Kth Smallest Element in BST problem ask you to find?
easy
A. The largest element in the Binary Search Tree
B. The height of the Binary Search Tree
C. The element that is the Kth smallest value in the Binary Search Tree
D. The number of nodes in the Binary Search Tree

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find the Kth smallest element, meaning the element that would appear in position K if the BST elements were sorted.
  2. Step 2: Recognize BST property

    In a BST, an inorder traversal visits nodes in ascending order, so the Kth visited node is the Kth smallest.
  3. Final Answer:

    The element that is the Kth smallest value in the Binary Search Tree -> Option C
  4. Quick Check:

    Kth smallest = Kth visited in inorder traversal [OK]
Hint: Inorder traversal gives sorted order; pick Kth node [OK]
Common Mistakes:
  • Confusing Kth smallest with Kth largest
  • Ignoring BST property and sorting separately
  • Using preorder or postorder traversal instead of inorder
2. Which of the following C# method signatures correctly represents a function to find the Kth smallest element in a BST node class named TreeNode?
easy
A. public int KthSmallest(TreeNode root, int k)
B. public void KthSmallest(int root, int k)
C. public int KthSmallest(TreeNode root)
D. public int KthSmallest(int k)

Solution

  1. Step 1: Identify correct parameter types

    The method needs the root node of type TreeNode and an integer k to find the Kth smallest element.
  2. Step 2: Check return type and parameters

    The method returns an int (the value of the Kth smallest node) and takes TreeNode root and int k as parameters.
  3. Final Answer:

    public int KthSmallest(TreeNode root, int k) -> Option A
  4. Quick Check:

    Correct signature includes root node and k as parameters [OK]
Hint: Method needs root node and k as inputs, returns int [OK]
Common Mistakes:
  • Using void return type instead of int
  • Missing root node parameter
  • Using wrong parameter types
3. Given the BST below and k = 3, what will the following C# code print?

class TreeNode {
  public int val;
  public TreeNode left, right;
  public TreeNode(int v) { val = v; }
}

// BST structure:
//       5
//      / \
//     3   7
//    / \   \
//   2   4   8

int KthSmallest(TreeNode root, int k) {
  List<int> vals = new List<int>();
  void Inorder(TreeNode node) {
    if (node == null) return;
    Inorder(node.left);
    vals.Add(node.val);
    Inorder(node.right);
  }
  Inorder(root);
  return vals[k - 1];
}

TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.right.right = new TreeNode(8);

Console.WriteLine(KthSmallest(root, 3));
medium
A. 4
B. 3
C. 5
D. 7

Solution

  1. Step 1: Perform inorder traversal of BST

    Inorder traversal visits nodes in ascending order: 2, 3, 4, 5, 7, 8.
  2. Step 2: Find the 3rd element in the sorted list

    The 3rd element (index 2) is 4.
  3. Final Answer:

    4 -> Option A
  4. Quick Check:

    Inorder sorted list = [2,3,4,5,7,8], 3rd element = 4 [OK]
Hint: Inorder traversal sorts BST; pick element at index k-1 [OK]
Common Mistakes:
  • Using preorder or postorder traversal order
  • Off-by-one error in indexing k-1
  • Confusing left and right subtree values
4. The following code attempts to find the Kth smallest element in a BST but fails to stop the traversal early after finding the Kth element. What is the main issue?

int KthSmallest(TreeNode root, int k) {
  int count = 0;
  int result = -1;
  void Inorder(TreeNode node) {
    if (node == null) return;
    Inorder(node.left);
    count++;
    if (count == k) {
      result = node.val;
      return;
    }
    Inorder(node.right);
  }
  Inorder(root);
  return result;
}
medium
A. The function does not handle empty trees
B. The variable count is not incremented correctly
C. The result variable is not initialized
D. The return inside Inorder does not stop the entire traversal

Solution

  1. Step 1: Analyze the recursive Inorder function

    The return statement inside Inorder only exits the current call, not the entire traversal, so traversal continues after finding the Kth element.
  2. Step 2: Understand why this is problematic

    Continuing traversal after setting result wastes time and space; no mechanism to stop recursion early.
  3. Final Answer:

    The return inside Inorder does not stop the entire traversal -> Option D
  4. Quick Check:

    Return in recursion stops only current call, not whole traversal [OK]
Hint: Return in recursion stops only one call, not full traversal [OK]
Common Mistakes:
  • Assuming return stops all recursion
  • Not using a flag to stop traversal after finding element
  • Ignoring null root case
5. You want to find the Kth smallest element in a BST but the tree is very large and you want to optimize for time and space. Which approach is best?

Options:
A) Use an iterative inorder traversal with a stack and stop when the Kth element is found.
B) Perform a full inorder traversal and store all elements in a list, then return the Kth element.
C) Convert the BST to a sorted array by any method, then binary search for the Kth element.
D) Use preorder traversal and count nodes until K is reached.
hard
A. Perform full inorder traversal and store all elements
B. Use iterative inorder traversal with stack, stop at Kth element
C. Convert BST to sorted array then binary search for Kth element
D. Use preorder traversal and count nodes until K is reached

Solution

  1. Step 1: Evaluate full inorder traversal approach

    Storing all elements uses extra space and time, not efficient for large trees.
  2. Step 2: Consider iterative inorder traversal with early stop

    This approach uses a stack to traverse nodes in order and stops immediately after finding the Kth smallest, saving time and space.
  3. Step 3: Analyze other options

    Binary search requires sorted array, which needs full traversal first; preorder traversal does not guarantee sorted order.
  4. Final Answer:

    Use iterative inorder traversal with stack, stop at Kth element -> Option B
  5. Quick Check:

    Iterative inorder + early stop = efficient Kth smallest search [OK]
Hint: Iterative inorder with stack stops early, saves time and space [OK]
Common Mistakes:
  • Using full traversal wasting memory
  • Using preorder which is unsorted
  • Trying binary search without sorted array
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard