Advertisement
kokokozhina

tree_1

Apr 19th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <set>
  5. #include <stdio.h>
  6.  
  7. using namespace std;
  8. //create the tree, display elements, using the inorder bypass, do exercise, then display new tree
  9.  
  10. struct tree{
  11. int inf;
  12. tree *left;
  13. tree *right;
  14. tree *par;
  15. };
  16.  
  17. tree *node(int x){
  18. tree *n = new tree;
  19. n->inf = x;
  20. n->left = NULL;
  21. n->right = NULL;
  22. n->par = NULL;
  23. return n;
  24. }
  25.  
  26. void insert(tree *&tr, int x){//only elements with different values
  27. tree* n = node(x);
  28. if(!tr) tr = n;
  29. else{
  30. tree* y = tr;
  31. while(y){
  32. if(n->inf > y->inf)
  33. if(y->right)
  34. y = y->right;
  35. else{
  36. n->par = y;
  37. y->right = n;
  38. break;
  39. }
  40. else
  41. if(n->inf < y->inf)
  42. if(y->left)
  43. y = y->left;
  44. else{
  45. n->par = y;
  46. y->left = n;
  47. break;
  48. }
  49. else break;
  50. }
  51. }
  52. }
  53.  
  54. void inorder(tree *tr){
  55. if(tr){
  56. inorder(tr->left);
  57. cout << tr->inf << " ";
  58. inorder(tr->right);
  59. }
  60. }
  61.  
  62. void for_sum(tree *tr, int &sum){
  63. if(tr){
  64. for_sum(tr->left, sum);
  65. sum += tr->inf;
  66. for_sum(tr->right, sum);
  67. }
  68. }
  69.  
  70. int main()
  71. {
  72. #ifdef _DEBUG
  73. freopen("input.txt", "r", stdin);
  74. freopen("output.txt", "w", stdout);
  75. #endif
  76. //count the sum of nodes
  77. int n;
  78. cin >> n;
  79. tree* Tree = NULL;
  80. cout << n << endl;
  81. for(int i = 0; i < n; i++){
  82. int cur; cin >> cur;
  83. insert(Tree, cur);
  84. }
  85. inorder(Tree);
  86. int res = 0;
  87. for_sum(Tree, res);
  88. cout << "Sum of nodes is " << res << endl;
  89.  
  90. return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement