fork download
  1.  
  2. #include <iostream>
  3. #include <vector>
  4. #include <cmath>
  5. #include <algorithm>
  6.  
  7. using namespace std;
  8.  
  9. struct Node {
  10. int data;
  11. Node *left, *right;
  12. Node(int val) : data(val), left(nullptr), right(nullptr) {}
  13. };
  14.  
  15. struct BST {
  16. Node* root = nullptr;
  17. int size = 0;
  18.  
  19. // TODO: Cài đặt hàm chèn phần tử x
  20. void insert(int x) {
  21. // Sinh viên hoàn thành
  22. }
  23.  
  24. // TODO: Cài đặt hàm tìm kiếm x, trả về true/false
  25. bool search(int x) {
  26. // Sinh viên hoàn thành
  27. return false;
  28. }
  29.  
  30. // TODO: Cài đặt hàm xóa phần tử x
  31. void remove(int x) {
  32. // Sinh viên hoàn thành
  33. }
  34.  
  35. // TODO: Tính chiều cao của cây
  36. int getHeight(Node* node) {
  37. // Sinh viên hoàn thành
  38. return -1;
  39. }
  40.  
  41. // TODO: Duyệt In-order
  42. void inOrder(Node* node, vector<int>& res) {
  43. // Sinh viên hoàn thành
  44. }
  45.  
  46. // TODO: Duyệt Pre-order
  47. void preOrder(Node* node, vector<int>& res) {
  48. // Sinh viên hoàn thành
  49. }
  50.  
  51. // TODO: Duyệt Post-order
  52. void postOrder(Node* node, vector<int>& res) {
  53. // Sinh viên hoàn thành
  54. }
  55.  
  56. // TODO: Tìm giá trị trong cây gần x nhất
  57. int findClosest(int x) {
  58. // Sinh viên hoàn thành
  59. return 0;
  60. }
  61.  
  62. // Helper function để gọi từ main
  63. void printOrder(int type) {
  64. vector<int> res;
  65. if (type == 5) inOrder(root, res);
  66. else if (type == 6) preOrder(root, res);
  67. else if (type == 7) postOrder(root, res);
  68.  
  69. for (int i = 0; i < res.size(); ++i) {
  70. cout << res[i] << (i == res.size() - 1 ? "" : " ");
  71. }
  72. cout << endl;
  73. }
  74. };
  75.  
  76. int main() {
  77. ios_base::sync_with_stdio(false);
  78. cin.tie(NULL);
  79.  
  80. int Q;
  81. cin >> Q;
  82. BST tree;
  83.  
  84. while (Q--) {
  85. int type, x;
  86. cin >> type;
  87. if (type == 1) {
  88. cin >> x;
  89. tree.insert(x);
  90. } else if (type == 2) {
  91. cin >> x;
  92. cout << (tree.search(x) ? "Yes" : "No") << "\n";
  93. } else if (type == 3) {
  94. cin >> x;
  95. tree.remove(x);
  96. } else if (type == 4) {
  97. cout << tree.getHeight(tree.root) << "\n";
  98. } else if (type >= 5 && type <= 7) {
  99. tree.printOrder(type);
  100. } else if (type == 8) {
  101. cin >> x;
  102. if (tree.root) cout << tree.findClosest(x) << "\n";
  103. } else if (type == 9) {
  104. cout << tree.size << "\n";
  105. }
  106. }
  107. return 0;
  108. }
  109.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Standard output is empty