Kth Smallest Element in a BST
You are given the root of a binary tree. Return the k-th smallest value in the BST, counting from 1 (so k = 1 is the smallest). In a binary search tree every value in a left subtree is smaller than its node and every value in a right subtree is larger.
Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.
Example 1
root [3,1,4,null,2]
k 1
returns 1
The values in order are 1, 2, 3, 4. The 1st smallest is 1.
Example 2
root [5,3,6,2,4,null,null,1]
k 3
returns 3
In order: 1, 2, 3, 4, 5, 6. The 3rd is 3.
Constraints
1 <= k <= number of nodes <= 100-1000 <= node.val <= 1000- The tree is a valid binary search tree.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.