fork download
  1. //size of tree
  2. #include<iostream>
  3. #include<queue>
  4. using namespace std;
  5. class node
  6. {
  7. public:
  8. int data;
  9. node *left;
  10. node *right;
  11. };
  12. class tree
  13. {
  14. node *root;
  15. queue <node*>q;
  16. int auxi(node *root);
  17. public:
  18. tree();
  19. int size_tree();
  20. void insert(int data);
  21. };
  22. tree::tree()
  23. {
  24. root=NULL;
  25. }
  26. void tree::insert(int data)
  27. {
  28. node *temp=new node;
  29. temp->left=temp->right=NULL;
  30. temp->data=data;
  31. if(root==NULL)
  32. {
  33. root=temp;
  34. q.push(temp);
  35. return;
  36. }
  37. else
  38. {
  39. node *curr;
  40. while(!q.empty())
  41. {
  42. curr=q.front();
  43. if(curr->left==NULL)
  44. {
  45. curr->left=temp;
  46. q.push(temp);
  47. return;
  48. }
  49. if(curr->right==NULL)
  50. {
  51. curr->right=temp;
  52. q.push(temp);
  53. return;
  54. }
  55. q.pop();
  56. }
  57. }
  58. }
  59. //Function for calculating size of tree
  60. int tree::size_tree()
  61. {
  62. return auxi(root);
  63. }
  64. int tree::auxi(node *root)
  65. {
  66. if(root==NULL)
  67. {
  68. return 0;
  69. }
  70. if(root!=NULL)
  71. {
  72. return auxi(root->left)+auxi(root->right)+1;
  73. }
  74. }
  75. int main()
  76. {
  77. int y;
  78. tree t;
  79. t.insert(1);
  80. t.insert(2);
  81. t.insert(3);
  82. t.insert(4);
  83. t.insert(5);
  84. t.insert(6);
  85. y=t.size_tree();
  86. cout<<y<<" ";
  87. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
6