fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // Define the structure of a tree node
  5. struct Node {
  6. int data;
  7. struct Node* left;
  8. struct Node* right;
  9. };
  10.  
  11. // Function to create a new node
  12. struct Node* createNode(int data) {
  13. struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  14. newNode->data = data;
  15. newNode->left = NULL;
  16. newNode->right = NULL;
  17. return newNode;
  18. }
  19.  
  20. // Function to calculate the size of the tree
  21. int calculateSize(struct Node* root) {
  22. if (root == NULL)
  23. return 0; // Base case: an empty tree has size 0
  24. return calculateSize(root->left) + calculateSize(root->right) + 1;
  25. }
  26.  
  27. int main() {
  28. // Creating the tree shown in your image
  29. struct Node* root = createNode(5);
  30. root->left = createNode(1);
  31. root->right = createNode(6);
  32. root->left->left = createNode(3);
  33. root->right->left = createNode(7);
  34. root->right->right = createNode(4);
  35.  
  36. // Calculate the size of the tree
  37. int size = calculateSize(root);
  38.  
  39. // Output the size
  40. printf("The size of the tree is: %d\n", size);
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
The size of the tree is: 6