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.

Try It Yourself
redirect icon

[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

C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;
    Node(int x)
    {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Recursive function to find the
// size of binary tree.
int getSize(Node *root)
{
    if (root == nullptr)
        return 0;

    // Find the size of left and right
    // subtree.
    int left = getSize(root->left);
    int right = getSize(root->right);

    // return the size of curr subtree.
    return left + right + 1;
}

int main()
{

    // Constructed binary tree is
    //         5
    //        / \
    //       1   6
    //      /   / \
    //     3   7   4

    Node *root = new Node(5);
    root->left = new Node(1);
    root->right = new Node(6);

    root->left->left = new Node(3);

    root->right->left = new Node(7);
    root->right->right = new Node(4);

    cout << getSize(root) << endl;

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node *left;
    struct Node *right;
};

// Recursive function to find the
// size of binary tree.
int getSize(struct Node *root)
{
    if (root == NULL)
        return 0;

    // Find the size of left and right
    // subtree.
    int left = getSize(root->left);
    int right = getSize(root->right);

    // return the size of curr subtree.
    return left + right + 1;
}

// Function to create Node
struct Node *createNode(int x)
{
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main()
{

    // Constructed binary tree is
    //         5
    //        / \
    //       1   6
    //      /   / \
    //     3   7   4
    
    struct Node *root = createNode(5);
    root->left = createNode(1);
    root->right = createNode(6);
    
    root->left->left = createNode(3);
    
    root->right->left = createNode(7);
    root->right->right = createNode(4);

    printf("%d\n", getSize(root));

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int x)
    {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Recursive function to find the
    // size of binary tree.
    static int getSize(Node root)
    {
        if (root == null)
            return 0;

        // Find the size of left and right
        // subtree.
        int left = getSize(root.left);
        int right = getSize(root.right);

        // return the size of curr subtree.
        return left + right + 1;
    }

    public static void main(String[] args)
    {

        // Constructed binary tree is
        //         5
        //        / \
        //       1   6
        //      /   / \
        //     3   7   4
        
        Node root = new Node(5);
        root.left = new Node(1);
        root.right = new Node(6);

        root.left.left = new Node(3);

        root.right.left = new Node(7);
        root.right.right = new Node(4);

        System.out.println(getSize(root));
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Recursive function to find the
# size of binary tree.
def getSize(root):
    if root is None:
        return 0

    # Find the size of left and right
    # subtree.
    left = getSize(root.left)
    right = getSize(root.right)

    # return the size of curr subtree.
    return left + right + 1


if __name__ == "__main__":

    #  Constructed binary tree is
    #          5
    #         / \
    #        1   6
    #       /   / \
    #      3   7   4
    
    root = Node(5)
    root.left = Node(1)
    root.right = Node(6)

    root.left.left = Node(3)

    root.right.left = Node(7)
    root.right.right = Node(4)

    print(getSize(root))
C#
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x)
    {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Recursive function to find the
    // size of binary tree.
    static int getSize(Node root)
    {
        if (root == null)
            return 0;

        // Find the size of left and right
        // subtree.
        int left = getSize(root.left);
        int right = getSize(root.right);

        // return the size of curr subtree.
        return left + right + 1;
    }

    static void Main(string[] args)
    {

        // Constructed binary tree is
        //         5
        //        / \
        //       1   6
        //      /   / \
        //     3   7   4

        Node root = new Node(5);
        root.left = new Node(1);
        root.right = new Node(6);

        root.left.left = new Node(3);

        root.right.left = new Node(7);
        root.right.right = new Node(4);

        Console.WriteLine(getSize(root));
    }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Recursive function to find the
// size of binary tree.
function getSize(root)
{
    if (root === null)
        return 0;

    // Find the size of left and right
    // subtree.
    let left = getSize(root.left);
    let right = getSize(root.right);

    // return the size of curr subtree.
    return left + right + 1;
}

// Constructed binary tree is
//         5
//        / \
//       1   6
//      /   / \
//     3   7   4

let root = new Node(5);
root.left = new Node(1);
root.right = new Node(6);

root.left.left = new Node(3);

root.right.left = new Node(7);
root.right.right = new Node(4);

console.log(getSize(root));

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.

C++
#include <iostream>
using namespace std;

// Define Node class
class Node
{
  public:
    int data;
    Node *left;
    Node *right;
    Node(int x)
    {
        data = x;
        left = NULL;
        right = NULL;
    }
};

// BFS function to count nodes
int bfs(Node *root)
{
    int cnt = 0;

    // Create queue and push root
    queue<Node *> pq;
    pq.push(root);

    while (!pq.empty())
    {
        // Remove front node and increment count
        Node *node = pq.front();
        pq.pop();

        cnt += 1;

        // Add left child
        if (node->left)
        {
            pq.push(node->left);
        }

        // Add right child
        if (node->right)
        {
            pq.push(node->right);
        }
    }

    return cnt;
}

// Function to get size of the tree
int getSize(Node *root)
{
    if (root == NULL)
    {
        return 0;
    }

    return bfs(root);
}

// Main function
int main()
{

    // Constructed binary tree is
    //         5
    //        / \
    //       1   6
    //      /   / \
    //     3   7   4

    Node *root = new Node(5);
    root->left = new Node(1);
    root->right = new Node(6);

    root->left->left = new Node(3);

    root->right->left = new Node(7);
    root->right->right = new Node(4);

    cout << getSize(root) << endl;

    return 0;
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

#define N 100000
// Define Node structure
struct Node
{
    int data;
    struct Node *left;
    struct Node *right;
};

// Function to create a new node
struct Node *createNode(int x)
{
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

// Simple queue implementation using array
struct Node *queue[N];
int front = 0, rear = 0;

// Enqueue operation
void enqueue(struct Node *node)
{
    queue[rear++] = node;
}

// Dequeue operation
struct Node *dequeue()
{
    return queue[front++];
}

// Check if queue is empty
int isEmpty()
{
    return front == rear;
}

// BFS function to count nodes
int bfs(struct Node *root)
{
    int cnt = 0;

    // Push root node into queue
    enqueue(root);

    while (!isEmpty())
    {
        // Remove front node and increment count
        struct Node *node = dequeue();
        cnt++;

        // Add left child
        if (node->left)
            enqueue(node->left);

        // Add right child
        if (node->right)
            enqueue(node->right);
    }

    return cnt;
}

// Function to get size of tree
int getSize(struct Node *root)
{
    if (root == NULL)
        return 0;
    return bfs(root);
}

int main()
{
    // Constructed binary tree is
    //         5
    //        / \
    //       1   6
    //      /   / \
    //     3   7   4
    
    struct Node *root = createNode(5);
    root->left = createNode(1);
    root->right = createNode(6);
    root->left->left = createNode(3);
    root->right->left = createNode(7);
    root->right->right = createNode(4);

    printf("%d\n", getSize(root));

    return 0;
}
Java
import java.util.*;

// Define Node class
class Node {
    int data;
    Node left, right;

    Node(int x)
    {
        data = x;
        left = null;
        right = null;
    }
}

public class Main {

    // BFS function to count nodes
    static int bfs(Node root)
    {
        int cnt = 0;

        // Create queue and push root
        Queue<Node> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {

            // Remove front node and increment count
            Node node = q.poll();
            cnt++;

            // Add left child if not null
            if (node.left != null)
                q.add(node.left);

            // Add right child if not null
            if (node.right != null)
                q.add(node.right);
        }

        return cnt;
    }

    // Function to get size of the tree
    static int getSize(Node root)
    {
        if (root == null)
            return 0;
        return bfs(root);
    }

    // Main function
    public static void main(String[] args)
    {

        // Constructed binary tree is
        //         5
        //        / \
        //       1   6
        //      /   / \
        //     3   7   4

        Node root = new Node(5);
        root.left = new Node(1);
        root.right = new Node(6);
        root.left.left = new Node(3);
        root.right.left = new Node(7);
        root.right.right = new Node(4);

        System.out.println(getSize(root));
    }
}
Python
from collections import deque

# Define Node class
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


# BFS function for count nodes
def bfs(root):
    cnt = 0

    # Create queue and push root
    q = deque()
    q.append(root)

    while q:

        # Remove front node and increment count
        node = q.popleft()
        cnt += 1

        # Add left child
        if node.left:
            q.append(node.left)

        # Add right child
        if node.right:
            q.append(node.right)

    return cnt


# Function to get size of the tree
def getSize(root):
    if root is None:
        return 0
    return bfs(root)


# Driver code
if __name__ == "__main__":
    
    # Constructed binary tree is
    #         5
    #        / \
    #       1   6
    #      /   / \
    #     3   7   4
    
    root = Node(5)
    root.left = Node(1)
    root.right = Node(6)
    root.left.left = Node(3)
    root.right.left = Node(7)
    root.right.right = Node(4)

    print(getSize(root))
C#
using System;
using System.Collections.Generic;

// Define Node class
class Node {
    public int data;
    public Node left, right;

    public Node(int x)
    {
        data = x;
        left = null;
        right = null;
    }
}

class Program {

    // BFS function to count nodes
    static int bfs(Node root)
    {
        int cnt = 0;

        // Create queue and push root
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {

            // Remove front and increment count
            Node node = q.Dequeue();
            cnt++;

            // Add left child
            if (node.left != null)
                q.Enqueue(node.left);

            // Add right child
            if (node.right != null)
                q.Enqueue(node.right);
        }

        return cnt;
    }

    // Function to get size of the node
    static int getSize(Node root)
    {
        if (root == null)
            return 0;
        return bfs(root);
    }

    // Main function
    static void Main()
    {
        // Constructed binary tree is
        //         5
        //        / \
        //       1   6
        //      /   / \
        //     3   7   4

        Node root = new Node(5);
        root.left = new Node(1);
        root.right = new Node(6);
        root.left.left = new Node(3);
        root.right.left = new Node(7);
        root.right.right = new Node(4);

        Console.WriteLine(getSize(root));
    }
}
JavaScript
// Define Node class
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// BFS function to count nodes
function bfs(root)
{
    let cnt = 0;

    // Create queue and push root
    let q = [];
    q.push(root);

    while (q.length > 0) {

        // Remove front and increment count
        let node = q.shift();
        cnt++;

        // Add left child
        if (node.left)
            q.push(node.left);

        // Add right child
        if (node.right)
            q.push(node.right);
    }

    return cnt;
}

// Function to get size of the tree
function getSize(root)
{
    if (root === null)
        return 0;
    return bfs(root);
}

// Driver code

//  Constructed binary tree is
//         5
//        / \
//       1   6
//      /   / \
//     3   7   4

let root = new Node(5);
root.left = new Node(1);
root.right = new Node(6);
root.left.left = new Node(3);
root.right.left = new Node(7);
root.right.right = new Node(4);

console.log(getSize(root));

Output
6
Comment