fork download
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4. struct Node {
  5. int data;
  6. Node *left, *right;
  7. Node(int x){
  8. data = x;
  9. left = NULL;
  10. right = NULL;
  11. }
  12. };
  13.  
  14.  
  15. Node * insert(Node *root, int val){
  16. if(root == NULL){
  17. return new Node(val);
  18. }
  19. if(root->data < val){
  20. root->right = insert(root->right, val);
  21. }
  22. else if(root->data > val){
  23. root->left = insert(root->left, val);
  24. }
  25. return root;
  26. }
  27.  
  28. void post(Node *root){
  29. if(root == NULL) return;
  30. post(root->left);
  31. post(root->right);
  32. cout << root->data << " ";
  33.  
  34. }
  35.  
  36.  
  37. int main() {
  38. int test;
  39. cin >> test;
  40. while(test--){
  41. int n;
  42. cin >> n;
  43. Node *root = NULL;
  44. int x;
  45. for(int i = 0; i < n; i++){
  46. cin >> x;
  47. root = insert(root, x);
  48. }
  49. post(root);
  50. cout << endl;
  51.  
  52. }
  53. return 0;
  54. }
Success #stdin #stdout 0.01s 5380KB
stdin
2
5
40 30 35 80 100
8
40 30 32 35 80 90 100 120
stdout
35 30 100 80 40 
35 32 30 120 100 90 80 40