fork download
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. using namespace std;
  5.  
  6. struct Node {
  7. int data;
  8. Node *left, *right;
  9. };
  10.  
  11. Node* insert(Node*&, int);
  12. int sum_of_vertex(const Node*);
  13.  
  14. int main() {
  15. ifstream fin("input.txt");
  16. ofstream fout("output.txt");
  17. int d;
  18. Node* root = nullptr;
  19. while (fin >> d)
  20. insert(root, d);
  21. fout << sum_of_vertex(root);
  22. fin.close();
  23. fout.close();
  24. return 0;
  25. }
  26.  
  27. Node* insert(Node*& root, int d) {
  28. if (root == nullptr) {
  29. root = new Node;
  30. root->data = d;
  31. root->left = nullptr;
  32. root->right = nullptr;
  33. }
  34. else if (d < root->data)
  35. root->left = insert(root->left, d);
  36. else if (d > root->data)
  37. root->right = insert(root->right, d);
  38. return root;
  39. }
  40.  
  41. int sum_of_vertex(const Node* root) {
  42. int sum = 0, l, r;
  43. if (root) {
  44. l = (root->left != nullptr) ? sum_of_vertex(root->left) : 0;
  45. r = (root->right != nullptr) ? sum_of_vertex(root->right) : 0;
  46. sum += l + r + root->data;
  47. return sum;
  48. }
  49. return 0;
  50. }
Success #stdin #stdout 0s 4408KB
stdin
Standard input is empty
stdout
Standard output is empty