Never seen before solution


#1

/**

  • Definition for binary tree
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    /
    int C=0;
    void find(TreeNode
    A, int B,int &ans) {
    if(A==NULL)
    return ;
    find(A->left,B,ans);
    C++;if(C==B) ans= A->val; // counter for smallest Kth node
    find(A->right,B,ans);
    return;
    }
    int Solution::kthsmallest(TreeNode* A, int B) {
    C=0;
    int ans=-1;
    find(A,B,ans);
    return ans;
    }