Bird
Raised Fist0
DSA Cprogramming~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
↓
Inorder Traverse Left Subtree
↓
Visit Node: count++
↓
Is count == k?
No→Inorder Traverse Right Subtree
Yes↓
Return Node Value
↓
Done
We do an inorder traversal of the BST, counting nodes visited. When count reaches k, we return that node's value.
Execution Sample
DSA C
int count = 0;
int kthSmallest(Node* root, int k) {
  if (!root) return -1;
  int left = kthSmallest(root->left, k);
  if (left != -1) return left;
  count++;
  if (count == k) return root->val;
  return kthSmallest(root->right, k);
}
This code finds the kth smallest element by inorder traversal counting nodes.
Execution Table
StepOperationCurrent NodeCountReturn ValueVisual State
1Start at root50N/A5 / \ 3 7 / \ 2 4 8
2Traverse left subtree30N/A5 / \ 3 7 / \ 2 4 8
3Traverse left subtree20N/A5 / \ 3 7 / \ 2 4 8
4Visit node21N/A5 / \ 3 7 / \ 2 4 8
5Check if count == k (k=3)21No5 / \ 3 7 / \ 2 4 8
6Traverse right subtreenull1-15 / \ 3 7 / \ 2 4 8
7Return to node 331N/A5 / \ 3 7 / \ 2 4 8
8Visit node32N/A5 / \ 3 7 / \ 2 4 8
9Check if count == k (k=3)32No5 / \ 3 7 / \ 2 4 8
10Traverse right subtree42N/A5 / \ 3 7 / \ 2 4 8
11Visit node43N/A5 / \ 3 7 / \ 2 4 8
12Check if count == k (k=3)43Yes5 / \ 3 7 / \ 2 4 8
13Return node value4345 / \ 3 7 / \ 2 4 8
14Stop traversalN/A345 / \ 3 7 / \ 2 4 8
💡 Traversal stops when count reaches k=3 at node with value 4.
Variable Tracker
VariableStartAfter Step 4After Step 8After Step 11Final
count01233
current node5234N/A
return valueN/AN/AN/AN/A4
Key Moments - 3 Insights
Why do we return immediately when left subtree returns a value?
Because the kth smallest is found in the left subtree, no need to continue. See execution_table step 6 where left subtree returns -1 (not found), but at step 13 it returns 4 and traversal stops.
Why do we increment count after visiting a node?
Because inorder traversal visits nodes in ascending order. Counting after visiting ensures we track how many smallest elements we have seen. See steps 4, 8, and 11 where count increments.
What happens if k is larger than number of nodes?
The function returns -1 after full traversal, meaning kth smallest doesn't exist. This is shown in step 6 when traversal hits null and returns -1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of count at step 8?
A1
B2
C3
D0
💡 Hint
Check the 'Count' column at step 8 in execution_table.
At which step does the traversal find the kth smallest element?
AStep 4
BStep 11
CStep 13
DStep 12
💡 Hint
Look for the step where 'Return node value' happens with count == k.
If k was 2 instead of 3, at which step would the function return the value?
AStep 8
BStep 11
CStep 13
DStep 4
💡 Hint
Check when count equals 2 in the variable_tracker and execution_table.
Concept Snapshot
Kth Smallest Element in BST:
- Use inorder traversal (left, node, right)
- Keep a count of nodes visited
- When count == k, return node value
- Stops traversal early once found
- Returns -1 if k > total nodes
Full Transcript
To find the kth smallest element in a BST, we do an inorder traversal which visits nodes in ascending order. We keep a count of how many nodes we have visited. When the count reaches k, we return that node's value immediately and stop traversal. If the left subtree returns a valid value, we return it immediately to avoid unnecessary traversal. If k is larger than the number of nodes, we return -1. This method ensures efficient search by leveraging BST properties.

Practice

(1/5)
1. What does the term kth smallest element in a BST mean?
easy
A. The element that appears in the kth position when BST elements are sorted in ascending order
B. The element with the kth largest value in the BST
C. The element at the kth level of the BST
D. The element with the kth highest frequency in the BST

Solution

  1. Step 1: Understand BST property

    A Binary Search Tree (BST) stores elements so that left subtree has smaller values and right subtree has larger values.
  2. Step 2: Define kth smallest element

    The kth smallest element is the one that appears in the kth position when all elements are sorted in ascending order.
  3. Final Answer:

    The element that appears in the kth position when BST elements are sorted in ascending order -> Option A
  4. Quick Check:

    kth smallest = kth in sorted order [OK]
Hint: Think of inorder traversal to get sorted order [OK]
Common Mistakes:
  • Confusing kth smallest with kth largest
  • Thinking kth smallest means kth level node
  • Assuming frequency matters
2. Which of the following C function signatures is correct to find the kth smallest element in a BST node structure struct Node?
easy
A. void kthSmallest(int root, int k);
B. int kthSmallest(struct Node root, int k);
C. int kthSmallest(struct Node* root, int k);
D. int kthSmallest(struct Node* root);

Solution

  1. Step 1: Understand function parameters

    The function needs the root pointer to the BST and the integer k to find kth smallest.
  2. Step 2: Check parameter types

    Passing struct Node* for root and int for k is correct. Return type should be int for the element value.
  3. Final Answer:

    int kthSmallest(struct Node* root, int k); -> Option C
  4. Quick Check:

    Correct signature includes pointer and k parameter [OK]
Hint: Use pointer for tree root and int for k [OK]
Common Mistakes:
  • Passing root by value instead of pointer
  • Missing k parameter
  • Wrong return type or missing return
3. Given the BST below and k = 3, what is the output of the function kthSmallest(root, 3)?
      5
     / \
    3   7
   / \   \
  2   4   8
medium
A. 5
B. 4
C. 3
D. 7

Solution

  1. Step 1: Perform inorder traversal

    Inorder traversal of BST visits nodes in ascending order: 2, 3, 4, 5, 7, 8.
  2. Step 2: Identify 3rd element in traversal

    The 3rd element is 4.
  3. Final Answer:

    4 -> Option B
  4. Quick Check:

    Inorder 3rd element = 4 [OK]
Hint: Inorder traversal gives sorted order; pick kth element [OK]
Common Mistakes:
  • Counting nodes incorrectly in traversal
  • Confusing preorder or postorder with inorder
  • Choosing root or other node instead of kth
4. Consider this buggy C code snippet to find kth smallest element in BST:
int count = 0;
int kthSmallest(struct Node* root, int k) {
    if (!root) return -1;
    int left = kthSmallest(root->left, k);
    if (left != -1) return left;
    count++;
    if (count == k) return root->data;
    return kthSmallest(root->right, k);
}
What is the main issue with this code?
medium
A. Global variable 'count' causes incorrect results on multiple calls
B. Function does not handle empty tree
C. Returns -1 for valid kth element
D. Does not traverse right subtree

Solution

  1. Step 1: Analyze use of 'count'

    The variable 'count' is global and not reset between calls, causing wrong counts if function called multiple times.
  2. Step 2: Understand impact on results

    Because 'count' is not reset, subsequent calls may return wrong kth smallest element or fail.
  3. Final Answer:

    Global variable 'count' causes incorrect results on multiple calls -> Option A
  4. Quick Check:

    Global count not reset breaks repeated calls [OK]
Hint: Avoid global counters; pass as function argument [OK]
Common Mistakes:
  • Ignoring global variable side effects
  • Assuming function works for multiple calls
  • Not resetting count before each call
5. You have a BST with nodes containing duplicate values. How would you modify the standard kth smallest element algorithm to correctly find the kth smallest unique element?
hard
A. Use preorder traversal instead of inorder
B. Count all nodes including duplicates normally
C. Remove duplicates from BST before traversal
D. Use inorder traversal and skip duplicates by comparing with previous visited value

Solution

  1. Step 1: Understand duplicates in BST

    Duplicates appear as multiple nodes with same value; inorder traversal visits them in sorted order including duplicates.
  2. Step 2: Modify traversal to skip duplicates

    Track previous visited value during inorder traversal; only increment count when current value differs from previous.
  3. Step 3: Find kth unique element

    Increment count only for unique values; when count equals k, return current node's value.
  4. Final Answer:

    Use inorder traversal and skip duplicates by comparing with previous visited value -> Option D
  5. Quick Check:

    Skip duplicates by comparing previous value [OK]
Hint: Track previous value to count unique elements [OK]
Common Mistakes:
  • Counting duplicates as separate elements
  • Using preorder traversal which is not sorted
  • Trying to remove duplicates instead of skipping
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