The Wayback Machine - https://web.archive.org/web/20240623232542/https://www.geeksforgeeks.org/find-length-of-a-linked-list-iterative-and-recursive/
Open In App

Find Length of a Linked List (Iterative and Recursive)

Last Updated : 17 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Write a function to count the number of nodes in a given singly linked list

Examples: 

Input:

linkedlist_find_length

Input: 2->4->1->9->5->3->6
Output: 7 

Recommended Practice

An iterative approach for finding the length of the linked list:

Follow the given steps to solve the problem:

  • Initialize count as 0 
  • Initialize a node pointer, current = head.
  • Do following while current is not NULL
    • current = current -> next
    • Increment count by 1.
  • Return count 

Below is the implementation of the above approach:

C++




// Iterative C++ program to find length
// or count of nodes in a linked list
#include <bits/stdc++.h>
using namespace std;
 
/* Link list node */
class Node {
public:
    int data;
    Node* next;
};
 
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
    /* allocate node */
    Node* new_node = new Node();
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* Counts no. of nodes in linked list */
int getCount(Node* head)
{
    int count = 0; // Initialize count
    Node* current = head; // Initialize current
    while (current != NULL) {
        count++;
        current = current->next;
    }
    return count;
}
 
/* Driver code*/
int main()
{
    /* Start with the empty list */
    Node* head = NULL;
 
    /* Use push() to construct below list
    1->2->1->3->1 */
    push(&head;, 1);
    push(&head;, 3);
    push(&head;, 1);
    push(&head;, 2);
    push(&head;, 1);
 
    // Function call
    cout << "count of nodes is " << getCount(head);
    return 0;
}
 
// This is code is contributed by rathbhupendra


C




// Iterative C program to find length or count of nodes in a
// linked list
#include <stdio.h>
#include <stdlib.h>
 
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
 
/* Given a reference (pointer to pointer) to the head
  of a list and an int, push a new node on the front
  of the list. */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
 
    /* put in the data  */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* Counts no. of nodes in linked list */
int getCount(struct Node* head)
{
    int count = 0; // Initialize count
    struct Node* current = head; // Initialize current
    while (current != NULL) {
        count++;
        current = current->next;
    }
    return count;
}
 
/* Driver code*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
 
    /* Use push() to construct below list
     1->2->1->3->1  */
    push(&head;, 1);
    push(&head;, 3);
    push(&head;, 1);
    push(&head;, 2);
    push(&head;, 1);
 
    // Function call
    printf("count of nodes is %d", getCount(head));
    return 0;
}


Java




// Java program to count number of nodes in a linked list
 
/* Linked list Node*/
class Node {
    int data;
    Node next;
    Node(int d)
    {
        data = d;
        next = null;
    }
}
 
// Linked List class
class LinkedList {
    Node head; // head of list
 
    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Returns count of nodes in linked list */
    public int getCount()
    {
        Node temp = head;
        int count = 0;
        while (temp != null) {
            count++;
            temp = temp.next;
        }
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        /* Start with the empty list */
        LinkedList llist = new LinkedList();
        llist.push(1);
        llist.push(3);
        llist.push(1);
        llist.push(2);
        llist.push(1);
 
          // Function call
        System.out.println("Count of nodes is "
                           + llist.getCount());
    }
}


Python3




# A complete working Python program to find length of a
# Linked List iteratively
 
# Node class
 
 
class Node:
    # Function to initialise the node object
    def __init__(self, data):
        self.data = data  # Assign data
        self.next = None  # Initialize next as null
 
 
# Linked List class contains a Node object
class LinkedList:
 
    # Function to initialize head
    def __init__(self):
        self.head = None
 
    # This function is in LinkedList class. It inserts
    # a new node at the beginning of Linked List.
 
    def push(self, new_data):
 
        # 1 & 2: Allocate the Node &
        #     Put in the data
        new_node = Node(new_data)
 
        # 3. Make next of new Node as head
        new_node.next = self.head
 
        # 4. Move the head to point to new Node
        self.head = new_node
 
    # This function counts number of nodes in Linked List
    # iteratively, given 'node' as starting node.
 
    def getCount(self):
        temp = self.head  # Initialise temp
        count = 0  # Initialise count
 
        # Loop while end of linked list is not reached
        while (temp):
            count += 1
            temp = temp.next
        return count
 
 
# Driver code
if __name__ == '__main__':
    llist = LinkedList()
    llist.push(1)
    llist.push(3)
    llist.push(1)
    llist.push(2)
    llist.push(1)
     
    # Function call
    print("Count of nodes is :", llist.getCount())


C#




// C# program to count number
// of nodes in a linked list
using System;
 
/* Linked list Node*/
public class Node {
    public int data;
    public Node next;
    public Node(int d)
    {
        data = d;
        next = null;
    }
}
 
// Linked List class
public class LinkedList {
    Node head; // head of list
 
    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Returns count of nodes in linked list */
    public int getCount()
    {
        Node temp = head;
        int count = 0;
        while (temp != null) {
            count++;
            temp = temp.next;
        }
        return count;
    }
 
    // Driver code
    public static void Main()
    {
        /* Start with the empty list */
        LinkedList llist = new LinkedList();
        llist.push(1);
        llist.push(3);
        llist.push(1);
        llist.push(2);
        llist.push(1);
 
          // Function call
        Console.WriteLine("Count of nodes is "
                          + llist.getCount());
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript




<script>
// javascript program to count number of nodes in a linked list
 
/* Linked list Node*/
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
 
// Linked List class
var head; // head of list
 
    /* Inserts a new Node at front of the list. */
     function push(new_data) {
        /*
         * 1 & 2: Allocate the Node & Put in the data
         */
        var new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Returns count of nodes in linked list */
     function getCount() {
        var temp = head;
        var count = 0;
        while (temp != null) {
            count++;
            temp = temp.next;
        }
        return count;
    }
 
    /*
     * Driver program to test above functions. Ideally this function should be in a
     * separate user class. It is kept here to keep code compact
     */
     
        /* Start with the empty list */
        push(1);
        push(3);
        push(1);
        push(2);
        push(1);
 
        document.write("Count of nodes is " + getCount());
 
// This code contributed by Rajput-Ji
</script>


Output

count of nodes is 5

Time complexity: O(N), Where N is the size of the linked list
Auxiliary Space: O(1), As constant extra space is used.

A recursive approach for finding the length of the linked list:

Follow the given steps to solve the problem:

  • If the head is NULL, return 0.
  • Otherwise, return 1 + getCount(head->next) 

Below is the implementation of the above approach:

C++




// Recursive C++ program to find length
// or count of nodes in a linked list
#include <bits/stdc++.h>
using namespace std;
 
/* Link list node */
class Node {
public:
    int data;
    Node* next;
};
 
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
    /* allocate node */
    Node* new_node = new Node();
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* Recursively count number of nodes in linked list */
int getCount(Node* head)
{
    // Base Case
    if (head == NULL) {
        return 0;
    }
    // Count this node plus the rest of the list
    else {
        return 1 + getCount(head->next);
    }
}
 
/* Driver program to test count function*/
int main()
{
    /* Start with the empty list */
    Node* head = NULL;
 
    /* Use push() to construct below list
    1->2->1->3->1 */
    push(&head;, 1);
    push(&head;, 3);
    push(&head;, 1);
    push(&head;, 2);
    push(&head;, 1);
 
    /* Check the count function */
    cout << "Count of nodes is " << getCount(head);
    return 0;
}
 
// This is code is contributed by rajsanghavi9


Java




// Recursive Java program to count number of nodes in
// a linked list
 
/* Linked list Node*/
class Node {
    int data;
    Node next;
    Node(int d)
    {
        data = d;
        next = null;
    }
}
 
// Linked List class
class LinkedList {
    Node head; // head of list
 
    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Returns count of nodes in linked list */
    public int getCountRec(Node node)
    {
        // Base case
        if (node == null)
            return 0;
 
        // Count is this node plus rest of the list
        return 1 + getCountRec(node.next);
    }
 
    /* Wrapper over getCountRec() */
    public int getCount() { return getCountRec(head); }
 
    /* Driver program to test above functions. Ideally
       this function should be in a separate user class.
       It is kept here to keep code compact */
    public static void main(String[] args)
    {
        /* Start with the empty list */
        LinkedList llist = new LinkedList();
        llist.push(1);
        llist.push(3);
        llist.push(1);
        llist.push(2);
        llist.push(1);
 
        System.out.println("Count of nodes is "
                           + llist.getCount());
    }
}


Python3




# A complete working Python program to find length of a
# Linked List recursively
 
# Node class
 
 
class Node:
    # Function to initialise the node object
    def __init__(self, data):
        self.data = data  # Assign data
        self.next = None  # Initialize next as null
 
 
# Linked List class contains a Node object
class LinkedList:
 
    # Function to initialize head
    def __init__(self):
        self.head = None
 
    # This function is in LinkedList class. It inserts
    # a new node at the beginning of Linked List.
 
    def push(self, new_data):
 
        # 1 & 2: Allocate the Node &
        #        Put in the data
        new_node = Node(new_data)
 
        # 3. Make next of new Node as head
        new_node.next = self.head
 
        # 4. Move the head to point to new Node
        self.head = new_node
 
    # This function counts number of nodes in Linked List
    # recursively, given 'node' as starting node.
    def getCountRec(self, node):
        if (not node):  # Base case
            return 0
        else:
            return 1 + self.getCountRec(node.next)
 
    # A wrapper over getCountRec()
    def getCount(self):
        return self.getCountRec(self.head)
 
 
# Code execution starts here
if __name__ == '__main__':
    llist = LinkedList()
    llist.push(1)
    llist.push(3)
    llist.push(1)
    llist.push(2)
    llist.push(1)
    print('Count of nodes is :', llist.getCount())


C#




// Recursive C# program to count number of nodes in
// a linked list
using System;
 
/* Linked list Node*/
public class Node {
    public int data;
    public Node next;
    public Node(int d)
    {
        data = d;
        next = null;
    }
}
 
// Linked List class
public class LinkedList {
    Node head; // head of list
 
    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Returns count of nodes in linked list */
    public int getCountRec(Node node)
    {
        // Base case
        if (node == null)
            return 0;
 
        // Count is this node plus rest of the list
        return 1 + getCountRec(node.next);
    }
 
    /* Wrapper over getCountRec() */
    public int getCount() { return getCountRec(head); }
 
    /* Driver program to test above functions. Ideally
    this function should be in a separate user class.
    It is kept here to keep code compact */
    public static void Main(String[] args)
    {
        /* Start with the empty list */
        LinkedList llist = new LinkedList();
        llist.push(1);
        llist.push(3);
        llist.push(1);
        llist.push(2);
        llist.push(1);
 
        Console.WriteLine("Count of nodes is "
                          + llist.getCount());
    }
}
 
// This code is contributed 29AjayKumar


Javascript




<script>
// Recursive javascript program to count number of nodes in
// a linked list
 
/* Linked list Node*/
class Node {
    constructor(val) {
            this.data = val;
            this.next = null;
        }
    }
 
    // Linked List class
    var head; // head of list
 
    /* Inserts a new Node at front of the list. */
    function push( new_data) {
        /*
         * 1 & 2: Allocate the Node & Put in the data
         */
        var new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Returns count of nodes in linked list */
     function getCountRec(node) {
        // Base case
        if (node == null)
            return 0;
 
        // Count is this node plus rest of the list
        return 1 + getCountRec(node.next);
    }
 
    /* Wrapper over getCountRec() */
     function getCount() {
        return getCountRec(head);
    }
 
    /*
     * Driver program to test above functions. Ideally this function should be in a
     * separate user class. It is kept here to keep code compact
     */
     
        /* Start with the empty list */
     
        push(1);
        push(3);
        push(1);
        push(2);
        push(1);
 
        document.write("Count of nodes is " + getCount());
 
// This code contributed by gauravrajput1
</script>


Output

Count of nodes is 5

Time Complexity: O(N), As we are traversing the linked list only once.
Auxiliary Space: O(N), Extra space is used in the recursion call stack.

Recursive approach for finding the length of the linked list using constant space:

To solve the problem follow the below idea:

The above recursive approach can be modified to make it a tail recursive function and thus our auxiliary space will become O(1)

Below is the implementation of the above approach:

C++




// Tail Recursive C++ program to find length
// or count of nodes in a linked list
#include <bits/stdc++.h>
using namespace std;
 
/* Link list node */
class Node {
public:
    int data;
    Node* next;
};
 
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
    /* allocate node */
    Node* new_node = new Node();
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
// A tail recursive function to count the nodes of a linked
// list
// default value of the count is used as zero
int getCount(Node* head, int count = 0)
{
    // base case
    if (head == NULL)
        return count;
    // move the pointer to next node and increase the count
    return getCount(head->next, count + 1);
}
 
/* Driver code*/
int main()
{
    /* Start with the empty list */
    Node* head = NULL;
 
    /* Use push() to construct below list
    1->2->1->3->1 */
    push(&head;, 1);
    push(&head;, 3);
    push(&head;, 1);
    push(&head;, 2);
    push(&head;, 1);
 
    // Function call
    cout << "Count of nodes is " << getCount(head);
    return 0;
}
 
// This is code is contributed by Abhijeet Kumar


Java




// Tail Recursive Java program to count number of nodes in
// a linked list
 
/* Linked list Node*/
class Node {
    int data;
    Node next;
    Node(int d)
    {
        data = d;
        next = null;
    }
}
 
// Linked List class
class LinkedList {
    Node head; // head of list
 
    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Returns count of nodes in linked list */
    public int getCountRec(Node node, int count)
    {
        // Base case
        if (node == null)
            return count;
 
        // Move to the next node and increase count
        return getCountRec(node.next, 1 + count);
    }
 
    /* Wrapper over getCountRec() */
    public int getCount() { return getCountRec(head, 0); }
 
    // Driver code
    public static void main(String[] args)
    {
        LinkedList llist = new LinkedList();
        llist.push(1);
        llist.push(3);
        llist.push(1);
        llist.push(2);
        llist.push(1);
 
          // Function call
        System.out.println("Count of nodes is "
                           + llist.getCount());
    }
}
 
// This code was contributed by Abhijeet
// Kumar(abhijeet19403)


Python3




# A complete working Python3 program to find length of a
# Linked List using Tail recursion.
 
# Node class
 
 
class Node:
    # Function to initialise the node object
    def __init__(self, data):
        self.data = data  # Assign data
        self.next = None  # Initialize next as null
 
 
# Linked List class contains a Node object
class LinkedList:
 
    # Function to initialize head
    def __init__(self):
        self.head = None
 
    # This function is in LinkedList class. It inserts
    # a new node at the beginning of Linked List.
 
    def push(self, new_data):
 
        # 1 & 2: Allocate the Node &
        #     Put in the data
        new_node = Node(new_data)
 
        # 3. Make next of new Node as head
        new_node.next = self.head
 
        # 4. Move the head to point to new Node
        self.head = new_node
 
    # This function counts number of nodes in Linked List
    # recursively, given 'node' as starting node using Tail Recursion.
    def getCountRec(self, node, count=0):
        if (not node):  # Base case
            return count
        else:
            return self.getCountRec(node.next, count+1)
 
    # A wrapper over getCountRec()
    def getCount(self):
        return self.getCountRec(self.head)
 
 
# Driver code
if __name__ == '__main__':
    llist = LinkedList()
    llist.push(1)
    llist.push(3)
    llist.push(1)
    llist.push(2)
    llist.push(1)
     
    # Function call
    print('Count of nodes is :', llist.getCount())
 
    # This code is contributed by garinesrija.


C#




// Tail Recursive C# program to count number of nodes in
// a linked list
using System;
 
/* Linked list Node*/
public class Node {
    public int data;
    public Node next;
    public Node(int d)
    {
        data = d;
        next = null;
    }
}
 
// Linked List class
public class LinkedList {
    Node head; // head of list
 
    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Returns count of nodes in linked list */
    public int getCountRec(Node node, int count)
    {
        // Base case
        if (node == null)
            return count;
 
        // Move the pointer to next node and increase the
        // count
        return getCountRec(node.next, 1 + count);
    }
 
    /* Wrapper over getCountRec() */
    public int getCount() { return getCountRec(head, 0); }
 
    // Driver code
    public static void Main(String[] args)
    {
        LinkedList llist = new LinkedList();
        llist.push(1);
        llist.push(3);
        llist.push(1);
        llist.push(2);
        llist.push(1);
 
          // Function call
        Console.WriteLine("Count of nodes is "
                          + llist.getCount());
    }
}
 
// This code is contributed Abhijeet Kumar(abhijeet19403)


Javascript




<script>
// Tail Recursive javascript program to count number of nodes in
// a linked list
 
/* Linked list Node*/
class Node {
    constructor(val) {
            this.data = val;
            this.next = null;
        }
    }
 
    // Linked List class
    var head; // head of list
 
    /* Inserts a new Node at front of the list. */
    function push( new_data) {
        /*
         * 1 & 2: Allocate the Node & Put in the data
         */
        var new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Returns count of nodes in linked list */
     function getCountRec(node,var count) {
        // Base case
        if (node == null)
            return count;
 
        // Move the pointer to next node and increase the count
        return getCountRec(node.next,count+1);
    }
 
    /* Wrapper over getCountRec() */
     function getCount() {
        return getCountRec(head,0);
    }
 
    /*
     * Driver program to test above functions. Ideally this function should be in a
     * separate user class. It is kept here to keep code compact
     */
     
        /* Start with the empty list */
     
        push(1);
        push(3);
        push(1);
        push(2);
        push(1);
 
        document.write("Count of nodes is " + getCount());
 
// This code contributed by Abhijeet Kumar(abhijeet19403)
</script>


Output

Count of nodes is 5

Time Complexity: O(N), As we are traversing the list only once.
Auxiliary Space: O(N), In worst case the depth of recursion call stack will be N.



Previous Article
Next Article

Similar Reads

Check if linked list is sorted (Iterative and Recursive)
Given a Linked List, task is to check whether the Linked List is sorted in Descending order or not? Examples : Input : 8 -&gt; 7 -&gt; 5 -&gt; 2 -&gt; 1 Output : Yes Explanation : In given linked list, starting from head, 8 &gt; 7 &gt; 5 &gt; 2 &gt; 1. So, it is sorted in reverse order Input : 24 -&gt; 12 -&gt; 9 -&gt; 11 -&gt; 8 -&gt; 2 Output : N
8 min read
Search an element in a Linked List (Iterative and Recursive)
Given a linked list and a key 'X' in, the task is to check if X is present in the linked list or not. Examples: Input: 14-&gt;21-&gt;11-&gt;30-&gt;10, X = 14Output: YesExplanation: 14 is present in the linked list. Input: 6-&gt;21-&gt;17-&gt;30-&gt;10-&gt;8, X = 13Output: No Using O(N) Extra Space. The Approach: In this approach we use vector where
15+ min read
Count consonants in a string (Iterative and recursive methods)
Given a string, count total number of consonants in it. A consonant is an English alphabet character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, and g. Examples : Input : abc de Output : 3 There are three consonants b, c and d. Input : geeksforgeeks portal Output : 12 1. Iterative Method C/C++ Code // Iterative CPP p
7 min read
First uppercase letter in a string (Iterative and Recursive)
Given a string find its first uppercase letterExamples : Input : geeksforgeeKs Output : K Input : geekS Output : S Method 1: linear search Using linear search, find the first character which is capital C/C++ Code // C++ program to find the first // uppercase letter using linear search #include &lt;bits/stdc++.h&gt; using namespace std; // Function
6 min read
Function to copy string (Iterative and Recursive)
Given two strings, copy one string to another using recursion. We basically need to write our own recursive version of strcpy in C/C++ Examples: Input : s1 = "hello" s2 = "geeksforgeeks" Output : s2 = "hello" Input : s1 = "geeksforgeeks" s2 = "" Output : s2 = "geeksforgeeks" Iterative: Copy every character from s1 to s2 starting from index = 0 and
6 min read
Count half nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the half nodes (which has only one child) without using recursion? Note leaves should not be touched as they have both children as NULL. Input : Root of below treeOutput : 3 Nodes 7, 5 and 9 are half nodes as one of their child is Null. So count of half nodes in the above tree is 3 Iterative The idea is to
12 min read
Program for average of an array (Iterative and Recursive)
Given an array, the task is to find average of that array. Average is the sum of array elements divided by the number of elements. Examples : Input : arr[] = {1, 2, 3, 4, 5} Output : 3 Sum of the elements is 1+2+3+4+5 = 15 and total number of elements is 5. So average is 15/5 = 3 Input : arr[] = {5, 3, 6, 7, 5, 3} Output : 4.83333 Sum of the elemen
7 min read
Count full nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the full nodes (Nodes which have both children as not NULL) without using recursion and with recursion? Note leaves should not be touched as they have both children as NULL. Nodes 2 and 6 are full nodes has both child's. So count of full nodes in the above tree is 2 Method: Iterative The idea is to use leve
12 min read
Program to count vowels in a string (Iterative and Recursive)
Given a string, count the total number of vowels (a, e, i, o, u) in it. There are two methods to count total number of vowels in a string. Iterative Recursive Examples: Input : abc de Output : 2 Input : geeksforgeeks portal Output : 7Recommended PracticeVowel or NotTry It! 1. Iterative Method: Below is the implementation: C/C++ Code // C++ program
7 min read
Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
Given two binary trees. We need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of new tree. Example: Input: Tree 1 Tree 2 2 3 / \ / \ 1 4 6 1 / \ \ 5 2 7 Output: Merged tree: 5 / \ 7 5 / \ \ 5 2 7 No
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg