Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- using namespace std;
- struct Node {
- Node* l;
- Node* r;
- int val;
- Node(int val) :val(val), l(nullptr), r(nullptr){}
- };
- Node* root = nullptr;
- ifstream fin("input.txt");
- ofstream fout("output.txt");
- void add(int c_val, Node* cur) {
- if (cur == nullptr) {
- root = new Node(c_val);
- return;
- }
- if (c_val < cur->val) {
- if (cur->l == nullptr) {
- cur->l = new Node(c_val);
- return;
- }
- add(c_val, cur->l);
- }
- else if (c_val > cur->val) {
- if (cur->r == nullptr) {
- cur->r = new Node(c_val);
- return;
- }
- add(c_val, cur->r);
- }
- }
- void print(Node* cur) {
- if (cur == nullptr) return;
- if (cur->l == nullptr && cur->r == nullptr) {
- fout << cur->val << "\n";
- }
- print(cur->l);
- print(cur->r);
- }
- int main() {
- int a;
- fin >> a;
- while (a != 0) {
- add(a, root);
- fin >> a;
- }
- print(root);
- fin.close();
- fout.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment