Raslboyy

761

Oct 3rd, 2019
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. using namespace std;
  5.  
  6. struct Node {
  7.     Node* l;
  8.     Node* r;
  9.     int val;
  10.     Node(int val) :val(val), l(nullptr), r(nullptr){}
  11. };
  12.  
  13. Node* root = nullptr;
  14. ifstream fin("input.txt");
  15. ofstream fout("output.txt");
  16.  
  17. void add(int c_val, Node* cur) {
  18.     if (cur == nullptr) {
  19.         root = new Node(c_val);
  20.         return;
  21.     }
  22.     if (c_val < cur->val) {
  23.         if (cur->l == nullptr) {
  24.             cur->l = new Node(c_val);
  25.             return;
  26.         }
  27.         add(c_val, cur->l);
  28.     }
  29.     else if (c_val > cur->val) {
  30.         if (cur->r == nullptr) {
  31.             cur->r = new Node(c_val);
  32.             return;
  33.         }
  34.         add(c_val, cur->r);
  35.     }
  36. }
  37.  
  38. void print(Node* cur) {
  39.     if (cur == nullptr) return;
  40.     if (cur->l == nullptr && cur->r == nullptr) {
  41.         fout << cur->val << "\n";
  42.     }
  43.     print(cur->l);
  44.     print(cur->r);
  45. }
  46.  
  47. int main() {
  48.  
  49.     int a;
  50.     fin >> a;
  51.     while (a != 0) {
  52.         add(a, root);
  53.         fin >> a;
  54.     }
  55.     print(root);
  56.  
  57.  
  58.     fin.close();
  59.     fout.close();
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment