Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- template<typename T>
- struct node
- {
- node(T data) { field = data; }
- T field;
- node *left = nullptr;
- node *right = nullptr;
- };
- void output_in(node<int> *q) //in-order
- {
- if (q == nullptr) return;
- output_in(q->left);
- cout << q->field << " ";
- output_in(q->right);
- }
- void output_pre(node<int> *q) //pre-order
- {
- if (q == nullptr) return;
- cout << q->field << " ";
- output_pre(q->left);
- output_pre(q->right);
- }
- void output_post(node<int> *q) //post-order
- {
- if (q == nullptr) return;
- output_post(q->left);
- output_post(q->right);
- cout << q->field << " ";
- }
- void destroy_tree(node<int> *q)
- {
- if (q == nullptr) return;
- destroy_tree(q->left);
- destroy_tree(q->right);
- delete q;
- }
- int main()
- {
- node<int> *root = new node<int>(1);
- root->left = new node<int>(2);
- root->left->left = new node<int>(4);
- root->left->right = new node<int>(5);
- root->right = new node<int>(3);
- cout << "In-order:\t"; output_in(root); cout << endl;
- cout << "Pre-order:\t"; output_pre(root); cout << endl;
- cout << "Post-order:\t"; output_post(root); cout << endl;
- destroy_tree(root);
- return 0;
- }
Add Comment
Please, Sign In to add comment