classSolution { int res = -1; voidtravel(struct Node* node, int k, int& counter){ if(!node) return; if(counter > k) return; travel(node->left, k, counter); if(k == counter) res = node->data; counter++; travel(node->right, k, counter); }
public: // Return the Kth smallest element in the given BST intKthSmallestElement(Node *root, int K){ res = -1; int counter = 1; travel(root, K, counter); return res; } };