Raslboyy

760

Oct 3rd, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 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.  
  15. ifstream fin("input.txt");
  16. ofstream fout("output.txt");
  17.  
  18. void add(int cur_val, Node* cur) {
  19.     if (cur == nullptr) {
  20.         root = new Node(cur_val);
  21.         return;
  22.     }
  23.     if (cur_val < cur->val) {
  24.         if (cur->l == nullptr) {
  25.             cur->l = new Node(cur_val);
  26.             return;
  27.         }
  28.         add(cur_val, cur->l);
  29.     }
  30.     else if (cur_val > cur->val) {
  31.         if (cur->r == nullptr) {
  32.             cur->r = new Node(cur_val);
  33.             return;
  34.         }
  35.         add(cur_val, cur->r);
  36.     }
  37. }
  38.  
  39. void print(Node* cur) {
  40.     if (cur == nullptr) return;
  41.     print(cur->l);
  42.     fout << cur->val << "\n";
  43.     print(cur->r);
  44. }
  45.  
  46. int main() {
  47.  
  48.     int a; fin >> a;
  49.     while (a != 0) {
  50.         add(a, root);
  51.         fin >> a;
  52.     }
  53.     print(root);
  54.  
  55.     fin.close();
  56.     fout.close();
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment