Instructions
You are given the root of a binary search tree (BST) and a number k. Return the k-th smallest value in the tree. k counts from 1, so k = 1 means the smallest value.
In a BST, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. All values in the tree are different.
How the input is shown
A tree is shown as a list of values in level order: row by row from the top, and left to right in each row. null means "no child here", and nulls at the end are left out. For example, [4, 2, 7, null, 3] is a root 4 with left child 2 and right child 7, and 2 has only a right child, 3.
Your function receives the root as a TreeNode (fields val, left, right) and k as a number. It returns a number.
Hint: an in-order walk (left subtree, then the node, then the right subtree) visits the values of a BST from smallest to largest. Count the nodes as you visit them, and stop at the k-th one.
Examples
Example 1
- Input:
- [50,30,70,20,40,60,80], 3
- Output:
- 40
From smallest to largest the values are 20, 30, 40, 50, 60, 70, 80. The 3rd one is 40.
Example 2
- Input:
- [9,4,null,1,6,null,2], 2
- Output:
- 2
The values in order are 1, 2, 4, 6, 9. The smallest, 1, has a right child 2, and 2 is the 2nd smallest. It is not the parent 4.
Example 3
- Input:
- [15], 1
- Output:
- 15
The tree has one node, so its value is the smallest one.
Constraints
- The number of nodes
nis between1and40. 1 <= k <= n1 <= Node.val <= 1000- All values are different, and the tree is a valid BST.
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [50,30,70,20,40,60,80], 3
- Expected:
- 40
- Input:
- [9,4,null,1,6,null,2], 2
- Expected:
- 2
- Input:
- [15], 1
- Expected:
- 15
Run checks your code against the 3 examples. Submit checks it against all 153 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.