Given a binary search tree, please find the first k smaller nodes therein.
You may assume that tree and k are present, and 1≤k≤ tree summary points.
Sample
input: root = [2, 1, 3, null, null, null, null], k = 3
2
/
1 3
Output: 3
class Solution {
public:
TreeNode* ans;
TreeNode* kthNode(TreeNode* root, int k) {
if(!root) return root;
dfs(root,k);
return ans;
}
void dfs(TreeNode* root,int &k) {
if(!root) return;
dfs(root -> left,k);
k--;
if(!k) ans = root;
dfs(root -> right,k);
}
};