Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Just read the question carefully, then, there is no problem. BST.....
void inorder(TreeNode* root, int &res, int &idx,int k){ if (root==NULL || idx>=k) return; inorder(root->left,res,idx,k); idx++; if (idx ==k ) res = root->val; inorder(root->right,res,idx,k); } int kthSmallest(TreeNode* root, int k) { int res; int idx=0; inorder(root,res,idx,k); return res; }