Advertisement
a53

BSTQ

a53
Mar 20th, 2022
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct Node
  4. {
  5. int data;
  6. Node *left,*right;
  7. int lCount;
  8. Node(int x)
  9. {
  10. data=x;
  11. left=right=NULL;
  12. lCount=0;
  13. }
  14. };
  15. Node* root;
  16.  
  17. Node* insert(Node* root,int x)
  18. {
  19. if(root==NULL)
  20. return new Node(x);
  21. if(x<root->data)
  22. {
  23. root->left=insert(root->left,x);
  24. root->lCount++;
  25. }
  26. else
  27. if(x>=root->data)
  28. root->right=insert(root->right, x);
  29. return root;
  30. }
  31.  
  32. Node* kthSmallest(Node* root,int k)
  33. {
  34. if(root==NULL)
  35. return NULL;
  36. int count=root->lCount+1;
  37. if(count==k)
  38. return root;
  39. if(count>k)
  40. return kthSmallest(root->left,k);
  41. return kthSmallest(root->right,k-count);
  42. }
  43.  
  44. int main()
  45. {
  46. int n,c,nr;
  47. ifstream fin("bstq.in");
  48. fin>>n;
  49. ofstream fout("bstq.out");
  50. while(n--)
  51. {
  52. fin>>c>>nr;
  53. if(c==1)
  54. root=insert(root,nr);
  55. else
  56. {
  57. Node* res=kthSmallest(root,nr);
  58. if(res==NULL)
  59. fout<<0<<'\n';
  60. else
  61. fout<<res->data<<'\n';
  62. }
  63. }
  64. return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement