Find Size of Binary Tree in C
Size of Binary Tree
Size of Binary tree is defined as the number of nodes in the given tree. It can be easily calculated using recursion and tree traversals. In this article this problem is solved using recursion.
- If node is empty, return NULL.
- Otherwise, recursively call the size function for the left and right subtree.
- Return 1 + sum of left and right subtree.
Code in C based on above ALgorithm
struct node* left;
struct node* right;
struct node* newNode(int data)
struct node* node = (struct node*)
node->data = data;
node->left = NULL;
node->right = NULL;
int size(struct node* node)
return(size(node->left) + 1 + size(node->right));
struct node *root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);
root->left->left = newNode(40);
root->left->right = newNode(50);
printf("Size of the tree is %d", size(root));
Size of the tree is 5