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 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. void postorder(const unique_ptr<Node>& root) {
  43. if (!root) return; // Base case
  44. postorder(root->left);
  45. postorder(root->right);
  46. cout << root->data << " ";
  47. }
  48.  
  49. int main() {
  50. int t;
  51. cin >> t;
  52. int testCase = 1; // Track test case number
  53. while (t--) {
  54. int n;
  55. cin >> n;
  56. vector<int> a(n);
  57. for (int i = 0; i < n; i++) {
  58. cin >> a[i];
  59. }
  60. auto root = buildBST(a); // Store the BST root
  61. cout << "Test #" << testCase++ << ": ";
  62. postorder(root);
  63. cout << endl; // Add newline for clarity
  64. }
  65. return 0;
  66. }
Success #stdin #stdout 0.01s 5316KB
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
Test #1: 2 1 5 4 3 
Test #2: 4 5 3 2 7 8 6 1 
Test #3: 1 3 2 6 5 7 4