Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Count number of nodes in a complete Binary Tree

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given the root of a Complete Binary Tree consisting of N nodes, the task is to find the total number of nodes in the given Binary Tree.

Examples:

Input:

Output: 7

Input:

Output: 5

 

Naive Approach: The simple approach to solving the given tree is to perform the DFS Traversal on the given tree and count the number of nodes in it. After traversal, print the total count of nodes obtained.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a Tree Node
class node {
public:
    int data;
    node* left;
    node* right;
};
 
// Function to get the count of nodes
// in complete binary tree
int totalNodes(node* root)
{
    if (root == NULL)
        return 0;
 
    int l = totalNodes(root->left);
    int r = totalNodes(root->right);
 
    return 1 + l + r;
}
 
// Helper function to allocate a new node
// with the given data
node* newNode(int data)
{
    node* Node = new node();
    Node->data = data;
    Node->left = NULL;
    Node->right = NULL;
    return (Node);
}
 
// Driver Code
int main()
{
    node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(9);
    root->right->right = newNode(8);
    root->left->left->left = newNode(6);
    root->left->left->right = newNode(7);
    cout << totalNodes(root);
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
 
class GFG {
  // tree node
    static class node
    {
        public int data;
        public node left, right;
        public node(){
            data = 0;
            left = right = null;
        }
 
    }
 
// Function to get the count of nodes
// in complete binary tree
    static int totalNodes(node root)
    {
        if (root == null)
            return 0;
     
        int l = totalNodes(root.left);
        int r = totalNodes(root.right);
     
        return 1 + l + r;
    }
 
// Helper function to allocate a new node
// with the given data
    static node newNode(int data)
    {
        node temp = new node();
        temp.data = data;
        temp.left = temp.right = null;
        return temp;
    }
 
 
// Driver Code
    public static void main(String args[])
    {
        node root = newNode(1);
        root.left = newNode(2);
        root.right = newNode(3);
        root.left.left = newNode(4);
        root.left.right = newNode(5);
        root.right.left = newNode(9);
        root.right.right = newNode(8);
        root.left.left.left = newNode(6);
        root.left.left.right = newNode(7);
        System.out.println(totalNodes(root));
         
    }
}
 
// This code is contributed by poojaagarwal2.


Python




# Python program for the above approach
# Structure of a Tree Node
 
 
class node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
 
         
# Function to get the count of nodes
# in complete binary tree
def totalNodes(root):
  # Base case
    if(root == None):
        return 0
 
    # Find the left height and the
    # right heights
    l = totalNodes(root.left)
    r = totalNodes(root.right)
 
    return 1 + l + r
 
   
# Helper Function to allocate a new node
# with the given data
def newNode(data):
    Node = node(data)
    return Node
 
 
# Driver code
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.left = newNode(9)
root.right.right = newNode(8)
root.left.left.left = newNode(6)
root.left.left.right = newNode(7)
 
print(totalNodes(root))
 
# This code is contributed by Yash Agarwal(yashagarwal2852002)


Javascript




<script>
        //JavaScript code for the above approach
 
        // Structure of a Tree Node
        class Node {
            constructor(data) {
                this.data = data;
                this.left = null;
                this.right = null;
            }
        }
 
        // Function to get the count of nodes
        // in complete binary tree
        function totalNodes(root) {
            if (root === null) {
                return 0;
            }
 
            let l = totalNodes(root.left);
            let r = totalNodes(root.right);
 
            return 1 + l + r;
        }
 
        // Helper function to allocate a new node
        // with the given data
        function newNode(data) {
            return new Node(data);
        }
 
        // Driver Code
 
        let root = newNode(1);
        root.left = newNode(2);
        root.right = newNode(3);
        root.left.left = newNode(4);
        root.left.right = newNode(5);
        root.right.left = newNode(9);
        root.right.right = newNode(8);
        root.left.left.left = newNode(6);
        root.left.left.right = newNode(7);
        document.write(totalNodes(root));
 
 
 // This code is contributed by Potta Lokesh
 
    </script>


C#




//C# code for the above approach
using System;
 
class GFG
{
    // tree node
    public class node
    {
        public int data;
        public node left, right;
        public node()
        {
            data = 0;
            left = right = null;
        }
 
    }
 
    // Function to get the count of nodes
    // in complete binary tree
    static int totalNodes(node root)
    {
        if (root == null)
            return 0;
 
        int l = totalNodes(root.left);
        int r = totalNodes(root.right);
 
        return 1 + l + r;
    }
 
    // Helper function to allocate a new node
    // with the given data
    static node newNode(int data)
    {
        node temp = new node();
        temp.data = data;
        temp.left = temp.right = null;
        return temp;
    }
 
 
    // Driver Code
    static void Main(string[] args)
    {
        node root = newNode(1);
        root.left = newNode(2);
        root.right = newNode(3);
        root.left.left = newNode(4);
        root.left.right = newNode(5);
        root.right.left = newNode(9);
        root.right.right = newNode(8);
        root.left.left.left = newNode(6);
        root.left.left.right = newNode(7);
        Console.WriteLine(totalNodes(root));
 
    }
}


Output

9

Time Complexity: O(N) as in traversal all the nodes are visited

Reason:

  • Recurrence Relation: T(N) = 2*T(N/2) + O(1) 
  • Solve via Master’s Theorem, you will get O(N) as Time.

Auxiliary Space: O(h) = O(log N)  as height of CBT is LogN

Reason:

  • Recursion Stack Space (which takes elements up to the height of the tree)
  • As you will go left, left till the corner leaf node. All of these stay in the stack on top of one another.

Efficient Approach: The above approach can also be optimized by the fact that:
 

A complete binary tree can have at most (2h + 1 – 1) nodes in total where h is the height of the tree (This happens when all the levels are completely filled).

By this logic, in the first case, compare the left sub-tree height with the right sub-tree height. If they are equal it is a full tree, then the answer will be 2^height – 1. Otherwise, If they aren’t equal, recursively call for the left sub-tree and the right sub-tree to count the number of nodes. Follow the steps below to solve the problem:

  • Define a function left_height(root) and find the left height of the given Tree by traversing in the root’s left direction and store it in a variable, say leftHeight.
  • Define a function right_height(root) and find the right height of the given Tree by traversing in the root’s right direction and store it in a variable, say rightHeight.
  • Find the left and the right height of the given Tree for the current root value and if it is equal then return the value of (2height – 1) as the resultant count of nodes.
  • Otherwise, recursively call for the function for the left and right sub-trees and return the sum of them + 1 as the resultant count of nodes.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a Tree Node
class node {
public:
    int data;
    node* left;
    node* right;
};
 
node* newNode(int data);
 
// Function to get the left height of
// the binary tree
int left_height(node* node)
{
    int ht = 0;
    while (node) {
        ht++;
        node = node->left;
    }
    // Return the left height obtained
    return ht;
}
 
// Function to get the right height
// of the binary tree
int right_height(node* node)
{
    int ht = 0;
    while (node) {
        ht++;
        node = node->right;
    }
    // Return the right height obtained
    return ht;
}
 
// Function to get the count of nodes
// in complete binary tree
int TotalNodes(node* root)
{
    // Base Case
    if (root == NULL)
        return 0;
    // Find the left height and the
    // right heights
    int lh = left_height(root);
    int rh = right_height(root);
    // If left and right heights are
    // equal return 2^height(1<<height) -1
    if (lh == rh)
        return (1 << lh) - 1;
    // Otherwise, recursive call
    return 1 + TotalNodes(root->left)
           + TotalNodes(root->right);
}
 
// Helper function to allocate a new node
// with the given data
node* newNode(int data)
{
    node* Node = new node();
    Node->data = data;
    Node->left = NULL;
    Node->right = NULL;
    return (Node);
}
 
// Driver Code
int main()
{
    node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(9);
    root->right->right = newNode(8);
    root->left->left->left = newNode(6);
    root->left->left->right = newNode(7);
    cout << TotalNodes(root);
    return 0;
}
 
// This code is contributed by aditya kumar (adityakumar129)


C




// C program for the above approach
#include <stdio.h>
#include <stdlib.h>
 
// Structure of a Tree Node
typedef struct node {
    int data;
    struct node* left;
    struct node* right;
}node;
 
// Helper function to allocate a new node
// with the given data
node* newNode(int data)
{
  node * Node = (node *)malloc(sizeof(node));
    Node->data = data;
    Node->left = NULL;
    Node->right = NULL;
    return (Node);
}
 
// Function to get the left height of
// the binary tree
int left_height(node* node)
{
    int ht = 0;
    while (node) {
        ht++;
        node = node->left;
    }
    // Return the left height obtained
    return ht;
}
 
// Function to get the right height
// of the binary tree
int right_height(node* node)
{
    int ht = 0;
    while (node) {
        ht++;
        node = node->right;
    }
 
    // Return the right height obtained
    return ht;
}
 
// Function to get the count of nodes
// in complete binary tree
int TotalNodes(node* root)
{
    // Base Case
    if (root == NULL)
        return 0;
    // Find the left height and the
    // right heights
    int lh = left_height(root);
    int rh = right_height(root);
    // If left and right heights are
    // equal return 2^height(1<<height) -1
    if (lh == rh)
        return (1 << lh) - 1;
    // Otherwise, recursive call
    return 1 + TotalNodes(root->left) + TotalNodes(root->right);
}
 
// Driver Code
int main()
{
    node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(9);
    root->right->right = newNode(8);
    root->left->left->left = newNode(6);
    root->left->left->right = newNode(7);
    printf("%d",TotalNodes(root));
    return 0;
}
 
// This code is contributed by aditya kumar (adityakumar129)


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Structure of a Tree Node
static class node {
 
    int data;
    node left;
    node right;
};
 
 
// Function to get the left height of
// the binary tree
static int left_height(node node)
{
    int ht = 0;
    while (node!=null) {
        ht++;
        node = node.left;
    }
 
    // Return the left height obtained
    return ht;
}
 
// Function to get the right height
// of the binary tree
static int right_height(node node)
{
    int ht = 0;
    while (node!=null) {
        ht++;
        node = node.right;
    }
 
    // Return the right height obtained
    return ht;
}
 
// Function to get the count of nodes
// in complete binary tree
static int TotalNodes(node root)
{
 
    // Base Case
    if (root == null)
        return 0;
 
    // Find the left height and the
    // right heights
    int lh = left_height(root);
    int rh = right_height(root);
 
    // If left and right heights are
    // equal return 2^height(1<<height) -1
    if (lh == rh)
        return (1 << lh) - 1;
 
    // Otherwise, recursive call
    return 1 + TotalNodes(root.left)
           + TotalNodes(root.right);
}
 
// Helper function to allocate a new node
// with the given data
static node newNode(int data)
{
    node Node = new node();
    Node.data = data;
    Node.left = null;
    Node.right = null;
    return (Node);
}
 
// Driver Code
public static void main(String[] args)
{
    node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.left = newNode(9);
    root.right.right = newNode(8);
    root.left.left.left = newNode(6);
    root.left.left.right = newNode(7);
 
    System.out.print(TotalNodes(root));
 
}
}
 
// This code is contributed by shikhasingrajput


Python3




# Python program for the above approach
 
# Structure of a Tree Node
class node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key
 
# Function to get the left height of
# the binary tree
def left_height(node):
    ht = 0
    while(node):
        ht += 1
        node = node.left
         
     # Return the left height obtained
    return ht
 
# Function to get the right height
# of the binary tree
def right_height(node):
    ht = 0
    while(node):
        ht += 1
        node = node.right
         
    # Return the right height obtained
    return ht
 
# Function to get the count of nodes
# in complete binary tree
def TotalNodes(root):
   
  # Base case
    if(root == None):
        return 0
       
     # Find the left height and the
    # right heights
    lh = left_height(root)
    rh = right_height(root)
     
     # If left and right heights are
    # equal return 2^height(1<<height) -1
    if(lh == rh):
        return (1 << lh) - 1
       
     # Otherwise, recursive call
    return 1 + TotalNodes(root.left) + TotalNodes(root.right)
 
# Driver code
root = node(1)
root.left = node(2)
root.right = node(3)
root.left.left = node(4)
root.left.right = node(5)
root.right.left = node(9)
root.right.right = node(8)
root.left.left.left = node(6)
root.left.left.right = node(7)
 
print(TotalNodes(root))
 
# This code is contributed by parthmanchanda81


C#




// C# program for the above approach
using System;
 
public class GFG{
 
// Structure of a Tree Node
class node {
 
    public int data;
    public node left;
    public node right;
};
 
 
// Function to get the left height of
// the binary tree
static int left_height(node node)
{
    int ht = 0;
    while (node != null) {
        ht++;
        node = node.left;
    }
 
    // Return the left height obtained
    return ht;
}
 
// Function to get the right height
// of the binary tree
static int right_height(node node)
{
    int ht = 0;
    while (node != null) {
        ht++;
        node = node.right;
    }
 
    // Return the right height obtained
    return ht;
}
 
// Function to get the count of nodes
// in complete binary tree
static int TotalNodes(node root)
{
 
    // Base Case
    if (root == null)
        return 0;
 
    // Find the left height and the
    // right heights
    int lh = left_height(root);
    int rh = right_height(root);
 
    // If left and right heights are
    // equal return 2^height(1<<height) -1
    if (lh == rh)
        return (1 << lh) - 1;
 
    // Otherwise, recursive call
    return 1 + TotalNodes(root.left)
           + TotalNodes(root.right);
}
 
// Helper function to allocate a new node
// with the given data
static node newNode(int data)
{
    node Node = new node();
    Node.data = data;
    Node.left = null;
    Node.right = null;
    return (Node);
}
 
// Driver Code
public static void Main(String[] args)
{
    node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.left = newNode(9);
    root.right.right = newNode(8);
    root.left.left.left = newNode(6);
    root.left.left.right = newNode(7);
 
    Console.Write(TotalNodes(root));
}
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
        // Structure of a Tree Node
        class Node {
            constructor(data) {
                this.data = data;
                this.left = null;
                this.right = null;
            }
        };
 
 
        // Function to get the left height of
        // the binary tree
        function left_height(node) {
            let ht = 0;
            while (node) {
                ht++;
                node = node.left;
            }
 
            // Return the left height obtained
            return ht;
        }
 
        // Function to get the right height
        // of the binary tree
        function right_height(node) {
            let ht = 0;
            while (node) {
                ht++;
                node = node.right;
            }
 
            // Return the right height obtained
            return ht;
        }
 
        // Function to get the count of nodes
        // in complete binary tree
        function TotalNodes(root) {
 
            // Base Case
            if (root == null)
                return 0;
 
            // Find the left height and the
            // right heights
            let lh = left_height(root);
            let rh = right_height(root);
 
            // If left and right heights are
            // equal return 2^height(1<<height) -1
            if (lh == rh)
                return (1 << lh) - 1;
 
            // Otherwise, recursive call
            return 1 + TotalNodes(root.left)
                + TotalNodes(root.right);
        }
 
        // Helper function to allocate a new node
        // with the given data
 
        // Driver Code
        let root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(9);
        root.right.right = new Node(8);
        root.left.left.left = new Node(6);
        root.left.left.right = new Node(7);
 
        document.write(TotalNodes(root));
 
     // This code is contributed by Potta Lokesh
    </script>


Output

9

Time Complexity: O((log N)2)

  • Calculating the height of a tree with x nodes takes (log x) time.
  • Here, we are traversing through the height of the tree.
  • For each node, height calculation takes logarithmic time.
  • As the number of nodes is N, we are traversing log(N) nodes and calculating the height for each of them.
  • So the total complexity is (log N * log N) = (log N)2.

Auxiliary Space: O(log N)  because of Recursion Stack Space (which takes elements upto the maximum depth of a node in the tree)


My Personal Notes arrow_drop_up
Last Updated : 28 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials