CJCoding With Joseph
15free / daySign inCreate account

Find the Kth Smallest Value in a BST

Complete kthSmallest(int k) and its helper walkInOrder(Node node, int k) so the tree can answer the question: what is the k-th smallest value? k counts from 1, so k = 1 asks for the smallest value and k = size() asks for the largest.

Reminder: an in-order traversal reads a BST in sorted order. In a binary search tree every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger. An in-order traversal visits the left subtree, then the node, then the right subtree, at every node, so on a BST it reaches the values from smallest to largest.

        50
       /  \
     30    70
    /  \   / \
  20  40  60  80

In-order reaches 20 first, then 30, then 40, and so on. That means the k-th smallest value is simply the k-th node the walk reaches: keep a counter in the count field, add one each time the walk visits a node, and when it equals k, save that node's value in the answer field.

Requirements: 1. kthSmallest(int k) returns -1 when k is less than 1 or greater than size(). An empty tree has size 0, so it always returns -1. 2. Otherwise it resets count to 0 and answer to -1, calls walkInOrder(root, k), and returns answer. 3. walkInOrder(Node node, int k) goes left, then counts the node, then goes right, and it stops early when node is null or count has already reached k. 4. kthSmallest may be called many times on the same tree, so every call must start from fresh field values.

The Node class is provided - do not rename it and do not add public to it, because a Java source file may contain only one public class.

Do NOT write a main method.

Expected Output:

20
40
50
80

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Data Structures & AlgorithmsBinary Search Trees
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (sysout, psvm, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.