D_L3

Дървесни операции(първа част)

Jan 27th, 2024 (edited)
760
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. struct Node{
  9.     Node* right = nullptr;
  10.     Node* left = nullptr;
  11.     int value;
  12.     Node(int value) : value(value){}
  13. };
  14.  
  15. struct Tree{
  16.     Node* root = nullptr;
  17.    
  18.     void addNode(int num, Node* curr){
  19.         if(num == curr->value)
  20.             return;
  21.          if(curr->value > num){
  22.             if(curr->left)
  23.                 addNode(num, curr->left);
  24.             else
  25.                 curr->left = new Node(num);
  26.         }
  27.         else{
  28.             if(curr->right)
  29.                 addNode(num, curr->right);
  30.             else
  31.                 curr->right = new Node(num);
  32.         }
  33.     }
  34.    
  35.     void add(int num){
  36.         if(!root){
  37.             root = new Node(num);
  38.             return;
  39.         }
  40.         addNode(num, root);
  41.     }
  42.    
  43.     void print(Node* curr){
  44.         if(!curr){
  45.             return;
  46.         }
  47.        
  48.         cout << curr->value << " ";
  49.         print(curr->left);
  50.         print(curr->right);
  51.     }
  52. };
  53.  
  54. int main() {
  55.     Tree tree;
  56.     int n;
  57.     string command;
  58.     int a;
  59.     cin >> n;
  60.     for(int i = 0; i < n; i++){
  61.         cin >> command;
  62.         if(command == "add"){
  63.             cin >> a;
  64.             tree.add(a);
  65.         }
  66.         else{
  67.             tree.print(tree.root);
  68.         }
  69.     }
  70.     return 0;
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment