fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. struct Node {
  7. int data;
  8. unique_ptr<Node> left;
  9. unique_ptr<Node> right;
  10. Node(int x) : data(x), left(nullptr), right(nullptr) {}
  11. };
  12.  
  13. void insert(unique_ptr<Node>& root, int val) {
  14. if (!root) {
  15. root = make_unique<Node>(val);
  16. return;
  17. }
  18. if (root->data == val) {
  19. return; // Ignore duplicates
  20. } else if (root->data > val) {
  21. insert(root->left, val);
  22. } else {
  23. insert(root->right, val);
  24. }
  25. }
  26.  
  27. unique_ptr<Node> buildBST(vector<int>& a) {
  28. unique_ptr<Node> root = nullptr; // Initialize root to nullptr
  29. for (int i = 0; i < a.size(); i++) {
  30. insert(root, a[i]);
  31. }
  32. return root;
  33. }
  34.  
  35. void inorder(const unique_ptr<Node>& root) {
  36. if (!root) return; // Base case
  37. inorder(root->left);
  38. cout << root->data << " ";
  39. inorder(root->right);
  40. }
  41.  
  42. int main() {
  43. int t;
  44. cin >> t;
  45. while (t--) {
  46. int n;
  47. cin >> n;
  48. vector<int> a(n);
  49. for (int i = 0; i < n; i++) {
  50. cin >> a[i];
  51. }
  52. auto root = buildBST(a); // Store the returned root
  53. inorder(root); // Pass the root to inorder
  54. cout << endl; // Add newline for clarity between test cases
  55. }
  56. return 0;
  57. }
Success #stdin #stdout 0s 5320KB
stdin
3
5
3 1 4 2 5
8
1 6 2 3 8 5 7 4
7
4 7 2 5 3 6 1
stdout
1 2 3 4 5 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7