ulvis.paste.net

Paste Search Dynamic
Recent pastes
size of the tree
  1. // A recursive C++ program to
  2. // calculate the size of the tree
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. /* A binary tree node has data, pointer to left child
  7. and a pointer to right child */
  8. class node
  9. {
  10.         public:
  11.         int data;
  12.         node* left;
  13.         node* right;
  14. };
  15.  
  16. /* Helper function that allocates a new node with the
  17. given data and NULL left and right pointers. */
  18. node* newNode(int data)
  19. {
  20.         node* Node = new node();
  21.         Node->data = data;
  22.         Node->left = null;
  23.         Node->right = null;
  24.  
  25.         return(Node);
  26. }
  27.  
  28. /* Computes the number of nodes in a tree. */
  29. void size(node* node,int& count)
  30. {
  31.         if (node == null)
  32.                 return;
  33.         //cout<<"data "<<node->data<<endl;
  34.         size(node->left,count);
  35.         count++;
  36.         //cout<<"count "<<count<<endl;
  37.         size(node->right,count);
  38.  
  39. }
  40.  
  41. /* Driver code*/
  42. int main()
  43. {
  44.         node *root = newNode(1);
  45.         root->left = newNode(2);
  46.         root->right = newNode(3);
  47.         root->left->left = newNode(4);
  48.         root->left->right = newNode(5);
  49.         int count=0;
  50.         size(root,count);
  51.         cout << "Size of the tree is " <<count ;
  52.         return 0;
  53. }
  54.  
  55. // This code is contributed by rathbhupendra
  56.  
Parsed in 0.007 seconds