Heap based approach


#1
priority_queue<int> p;
void recur(TreeNode* root, int k){
    if(!root) return;
    if(p.size()>k) p.pop();
    p.push(root->val);
    recur(root->left,k);
    recur(root->right,k);
}

int Solution::kthsmallest(TreeNode* A, int B) {
    while(p.size()!=0) p.pop();
    recur(A,B);
    if(p.size()>B) p.pop();
    return p.top();
}

#2

why my code is not working
/**

  • Definition for binary tree

  • struct TreeNode {

  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    */
    priority_queue pq;
    void preorder(TreeNode *root,int k)
    {
    if(root==NULL) return ;

      pq.push(root->val);
    

    if(pq.size()>k) pq.pop();

    preorder(root->left,k);
    preorder(root->right,k);
    }
    int Solution::kthsmallest(TreeNode* A, int B) {
    preorder(A,B);
    return pq.top();
    }


#3

To get the sorted order, you have to use Inorder traversal, not preorder.