Facebook
From jakir, 2 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 263
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct BinaryTree{
  5.     int data;
  6.     BinaryTree *left;
  7.     BinaryTree *right;
  8.  
  9.     BinaryTree(int _data) : data(_data), left(nullptr), right(nullptr) {}
  10. };
  11.  
  12. BinaryTree* createTree(BinaryTree* root, int data) {
  13.     if(root == nullptr){
  14.         return new BinaryTree(data);
  15.     }
  16.     if(root->data < data){
  17.         root->left = createTree(root->left, data);
  18.     }
  19.     else {
  20.         root->right = createTree(root->right, data);
  21.     }
  22.     return root;
  23. }
  24.  
  25. void inorder(BinaryTree *root) {
  26.  
  27.     if(root == nullptr) {
  28.         return;
  29.     }
  30.     inorder(root->left);
  31.     cout << root->data << ' ';
  32.     inorder(root->right);
  33. }
  34.  
  35. void postorder(BinaryTree *root) {
  36.     if(root == nullptr) return;
  37.     postorder(root->left);
  38.     postorder(root->right);
  39.     cout << root->data << ' ';
  40. }
  41.  
  42. int main() {
  43.     BinaryTree* root = nullptr;
  44.     bool flag = true;
  45.     while(1) {
  46.         cout << "1. Insert noden";
  47.         cout << "2. Postorder traversaln";
  48.         cout << "3. Inorder traversaln";
  49.         cout << "4. Exitn";
  50.         int choice;
  51.         cin >> choice;
  52.  
  53.         switch(choice) {
  54.         case 1:
  55.             cout << "Enter the element you want to insert: ";
  56.             int  data;
  57.             cin >> data;
  58.             if(flag) {
  59.                 root = createTree(root, data);
  60.                 flag = false;
  61.             }
  62.             else createTree(root, data);
  63.             break;
  64.         case 2:
  65.             inorder(root);
  66.             cout << endl;
  67.             break;
  68.         case 3:
  69.             postorder(root);
  70.             cout << endl;
  71.             break;
  72.         case 4:
  73.             return 0;
  74.         default:
  75.             cout << "Invalid Option Chosenn";
  76.             break;
  77.         }
  78.     }
  79.  
  80.     return 0;
  81. }
  82.