VOOZH about

URL: https://www.geeksforgeeks.org/dsa/write-a-c-program-to-calculate-size-of-a-tree/

⇱ Size of a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Size of a Binary Tree

Last Updated : 24 Apr, 2026

Given a binary tree, find the size of the tree. The size of a tree is the number of nodes present in the tree.

Examples:

Input:

👁 check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves

Output: 6
Explanation: The number of nodes in the above binary tree is 6.

[Expected Approach] - By using Recursion - O(n) Time and O(h) Auxiliary Space

The idea is to recursively calculate the size of tree. For each node (starting from root node), calculate the size of left subtree and right subtree and return the size of current subtree (size of left subtree + size of right subtree + 1).

Consider the following tree for example to understand the flow.

👁 treee

getSize(5) = getSize(1) + getSize(6) + 1 = 2 + 3 + 1 = 6
because recursively
getSize(1) = getSize(3) + getSize(NULL) + 1 = 1 + 0 + 1 = 2
getSize(6) = getSize(7) + getSize(4) + 1 = 1 + 1 + 1 = 3
getSize(3) = getSize(NULL) + getSize(NULL) + 1 = 0 + 0 + 1 = 1
getSize(7) = getSize(NULL) + getSize(NULL) + 1 = 0 + 0 + 1 = 1
getSize(4) = getSize(NULL) + getSize(NULL) + 1 = 0 + 0 + 1 = 1


Output
6

[Alternate Approach] - Using Breadth First Search(BFS) - O(n) Time and O(n) Space

The idea is to traverse the tree level by level using a queue. Start from the root node, and for each node, visit it, increment the count, and add its left and right children to the queue. Continue this process until all nodes are visited. The total count at the end gives the size of the tree.

Dry run for the below tree structure:

👁 treee

Let us see all iterations of the main loop for the above tree.

  • Iter 1: Queue = [5], Pop = 5 and Count = 1 then Push = [1, 6]
  • Iter 2: Queue = [1, 6], Pop = 1 and Count = 2 then Push = [6, 3]
  • Iter 3: Queue = [6, 3], Pop = 6 and Count = 3 then Push = [3, 7, 4]
  • Iter 4: Queue = [3, 7, 4], Pop = 3 and Count = 4 then Push = [7,4]
  • Iter 5: Queue = [7,4], Pop = 7 and Count = 5 then Push = [4]
  • Iter 6: Queue = [4], Pop = 4 and Count = 6 then Push = []

Final answer is total nodes = 6.


Output
6
Comment
Article Tags: