Advertisement
RadioNurshat

Tree

May 26th, 2021
1,100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. //ПЕРВАЯ ЗАДАЧА
  4. struct Node {
  5.     Node* left;
  6.     Node* right;
  7.     int info;
  8. };
  9.  
  10. void AddLeft(Node* node, int data) {
  11.     node->left = new Node();
  12.     node->left->info = data;
  13. }
  14. void AddRight(Node* node, int data) {
  15.     node->right = new Node();
  16.     node->right->info = data;
  17. }
  18. void AddElement(Node* node, int data, int direction) {
  19.     if (direction == 1) {
  20.         AddLeft(node, data);
  21.     }
  22.     else {
  23.         AddRight(node, data);
  24.     }
  25. }
  26.  
  27.  
  28. //ВТОРАЯ ЗАДАЧА
  29. void print(Node* node, const std::string& prefix = "")
  30. {
  31.     if (node != nullptr)
  32.     {
  33.         std::cout << prefix << "   ";
  34.         std::cout << node->info << std::endl;
  35.         print(node->left, prefix + "   ");
  36.         print(node->right, prefix + "   ");
  37.     }
  38. }
  39.  
  40. //Третья задача
  41. void GetOddEvenCount(Node* node, int& odd, int& even) {
  42.     if (node->info % 2 == 0) {
  43.         even++;
  44.     }
  45.     else {
  46.         odd++;
  47.     }
  48.  
  49.     if (node->left != nullptr) {
  50.         GetOddEvenCount(node->left, odd, even);
  51.     }
  52.     if (node->right != nullptr) {
  53.         GetOddEvenCount(node->right, odd, even);
  54.     }
  55. }
  56.  
  57.  
  58.  
  59. int main()
  60. {
  61.     Node* root = new Node();
  62.     root->info = 1;
  63.     AddElement(root, 2, 1);
  64.     AddElement(root, 3, 0);
  65.     AddElement(root->right, 4, 1);
  66.     AddElement(root->right, 5, 0);
  67.     AddElement(root->right->right, 6, 1);
  68.     AddElement(root->right->right, 7, 0);
  69.  
  70.     print(root);
  71.  
  72.     int odd = 0;
  73.     int even = 0;
  74.     GetOddEvenCount(root, odd, even);
  75.  
  76.     std::cout << std::endl << odd << " " << even << std::endl;
  77.  
  78. }
  79.  
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement