fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. bool found = false;
  5.  
  6. class BST
  7. {
  8. public:
  9. long long data, index;
  10. BST *left, *right;
  11.  
  12. // Default constructor.
  13. BST();
  14.  
  15. // Parameterized constructor.
  16. BST(long long, long long);
  17.  
  18. // Insert function.
  19. BST* Insert(BST*, long long, long long);
  20.  
  21. // Inorder traversal.
  22. void IndexSearch(BST*);//, long long);
  23. };
  24.  
  25.  
  26. BST ::BST()
  27. : data(0)
  28. , left(NULL)
  29. , right(NULL)
  30. , index(1)
  31. {
  32. }
  33.  
  34. BST ::BST(long long value, long long i)
  35. {
  36. data = value;
  37. left = right = NULL;
  38. index = i;
  39. }
  40.  
  41.  
  42. BST* BST ::Insert(BST* root, long long index, long long value)
  43. {
  44. if (!root)
  45. {
  46. return new BST(value, index);
  47. }
  48.  
  49. if (value > root->data)
  50. {
  51. root->index += 1;
  52. root->right = Insert(root->right, index, value);
  53. }
  54. else
  55. {
  56. root->left = Insert(root->left, index + 1, value);
  57. }
  58.  
  59. return root;
  60. }
  61.  
  62. // Inorder traversal function.
  63. // This gives data in sorted order.
  64. void BST ::IndexSearch(BST* root)//, long long data)
  65. {
  66. if (!root || found) {
  67. return;
  68. }
  69. IndexSearch(root->right);//, data);
  70. cout << "index: " << root->index;
  71. cout << " data: " << root->data << endl;
  72. IndexSearch(root->left);//, data);
  73. }
  74.  
  75. // Driver code
  76. int main()
  77. {
  78. long long n, type, data;
  79. BST b, *root = NULL;
  80.  
  81. cin >> n;
  82.  
  83. while (n--) {
  84. cin >> type;
  85. cin >> data;
  86. if (!root) {
  87. if (type == 1) root = b.Insert(root, 1, data);
  88. else if (type == 2) cout << "Data tidak ada\n";
  89. }
  90. else {
  91. if (type == 1) {
  92. b.Insert(root, root->index, data);
  93. }
  94. /*else {
  95.   b.IndexSearch(root, data);
  96. if (!found) cout << "Data tidak ada\n";
  97.   }*/
  98. }
  99. found = false;
  100. }
  101. b.IndexSearch(root);
  102. return 0;
  103. }
Success #stdin #stdout 0s 5460KB
stdin
10
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
stdout
index: 9 data: 10
index: 9 data: 9
index: 9 data: 8
index: 9 data: 7
index: 9 data: 6
index: 9 data: 5
index: 9 data: 4
index: 9 data: 3
index: 9 data: 2
index: 10 data: 1