Batisk_AFF

Binary trees

Feb 23rd, 2021 (edited)
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. template<typename T>
  4. struct node
  5. {
  6.     node(T data) { field = data; }
  7.     T field;
  8.     node *left = nullptr;
  9.     node *right = nullptr;
  10. };
  11.  
  12.  
  13. void output_in(node<int> *q) //in-order
  14. {
  15.     if (q == nullptr) return;
  16.     output_in(q->left);
  17.     cout << q->field << " ";
  18.     output_in(q->right);
  19. }
  20.  
  21. void output_pre(node<int> *q) //pre-order
  22. {
  23.     if (q == nullptr) return;
  24.     cout << q->field << " ";
  25.     output_pre(q->left);
  26.     output_pre(q->right);
  27. }
  28.  
  29. void output_post(node<int> *q) //post-order
  30. {
  31.     if (q == nullptr) return;
  32.     output_post(q->left);
  33.     output_post(q->right);
  34.     cout << q->field << " ";
  35. }
  36.  
  37. void destroy_tree(node<int> *q)
  38. {
  39.     if (q == nullptr) return;
  40.     destroy_tree(q->left);
  41.     destroy_tree(q->right);
  42.     delete q;
  43. }
  44.  
  45. int main()
  46. {
  47.     node<int> *root = new node<int>(1);
  48.     root->left = new node<int>(2);
  49.     root->left->left = new node<int>(4);
  50.     root->left->right = new node<int>(5);
  51.     root->right = new node<int>(3);
  52.  
  53.     cout << "In-order:\t";     output_in(root);    cout << endl;
  54.     cout << "Pre-order:\t";   output_pre(root);   cout << endl;
  55.     cout << "Post-order:\t";  output_post(root);  cout << endl;
  56.  
  57.     destroy_tree(root);
  58.     return 0;
  59. }
Add Comment
Please, Sign In to add comment