The Wayback Machine - https://web.archive.org/web/20240927174927/https://www.geeksforgeeks.org/level-maximum-number-nodes/
Open In App

Level with maximum number of nodes

Last Updated : 20 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
82.66%
28.8K

Find the level in a binary tree that has the maximum number of nodes. The root is at level 0.

Examples: 

Input: 

Output : 2
Explanation:

Input:

Output:1
Explanation

 
Recommended Practice

Approach: It is known that in level order traversal of binary tree with queue, at any time our queue contains all elements of a particular level. So find level with maximum number of nodes in queue. 
BFS traversal is an algorithm for traversing or searching tree or graphs . It starts at the tree root , and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. 
So at any point the queue of BFS will contain elements of adjacent layers. So this makes the algorithm perfect for this problem.

Algorithm: 

  1. Create the tree, a queue to store the nodes and insert the root in the queue. Create variables level=0,count =0 and level_no=-1
  2. The implementation will be slightly different, all the elements of same level will be removed in a single iteration.
  3. Run a loop while size of queue is greater than 0. Get the size of queue (size) and store it. If size is greater than count then update count = size and level_no = level.
  4. Now run a loop size times, and pop one node from the queue and insert its childrens (if present).
  5. Increment level.

Implementation: 

C++




// C++ implementation to find the level
// having maximum number of Nodes
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree Node has data, pointer
   to left child and a pointer to right
   child */
struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
};
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return(node);
}
 
// function to find the level
// having maximum number of Nodes
int maxNodeLevel(Node *root)
{
    if (root == NULL)
        return -1;
 
    queue<Node *> q;
    q.push(root);
 
    // Current level
    int level = 0;
 
    // Maximum Nodes at same level
    int max = INT_MIN;
 
    // Level having maximum Nodes
    int level_no = 0;
 
    while (1)
    {
        // Count Nodes in a level
        int NodeCount = q.size();
 
        if (NodeCount == 0)
            break;
 
        // If it is maximum till now
        // Update level_no to current level
        if (NodeCount > max)
        {
            max = NodeCount;
            level_no = level;
        }
 
        // Pop complete current level
        while (NodeCount > 0)
        {
            Node *Node = q.front();
            q.pop();
            if (Node->left != NULL)
                q.push(Node->left);
            if (Node->right != NULL)
                q.push(Node->right);
            NodeCount--;
        }
 
        // Increment for next level
        level++;
    }
 
    return level_no;
}
 
// Driver program to test above
int main()
{
    // binary tree formation
    struct Node *root = newNode(2);      /*        2      */
    root->left        = newNode(1);      /*      /   \    */
    root->right       = newNode(3);      /*     1     3      */
    root->left->left  = newNode(4);      /*   /   \    \  */
    root->left->right = newNode(6);      /*  4     6    8 */
    root->right->right  = newNode(8);    /*       /       */
    root->left->right->left = newNode(5);/*      5        */
 
    printf("Level having maximum number of Nodes : %d",
            maxNodeLevel(root));
    return 0;
}


Java




// Java implementation to find the level
// having maximum number of Nodes
import java.util.*;
class GfG {
 
/* A binary tree Node has data, pointer
to left child and a pointer to right
child */
static class Node
{
    int data;
    Node left;
    Node right;
}
 
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    return(node);
}
 
// function to find the level
// having maximum number of Nodes
static int maxNodeLevel(Node root)
{
    if (root == null)
        return -1;
 
    Queue<Node> q = new LinkedList<Node> ();
    q.add(root);
 
    // Current level
    int level = 0;
 
    // Maximum Nodes at same level
    int max = Integer.MIN_VALUE;
 
    // Level having maximum Nodes
    int level_no = 0;
 
    while (true)
    {
        // Count Nodes in a level
        int NodeCount = q.size();
 
        if (NodeCount == 0)
            break;
 
        // If it is maximum till now
        // Update level_no to current level
        if (NodeCount > max)
        {
            max = NodeCount;
            level_no = level;
        }
 
        // Pop complete current level
        while (NodeCount > 0)
        {
            Node Node = q.peek();
            q.remove();
            if (Node.left != null)
                q.add(Node.left);
            if (Node.right != null)
                q.add(Node.right);
            NodeCount--;
        }
 
        // Increment for next level
        level++;
    }
 
    return level_no;
}
 
// Driver program to test above
public static void main(String[] args)
{
    // binary tree formation
     Node root = newNode(2);     /*     2     */
    root.left     = newNode(1);     /*     / \ */
    root.right     = newNode(3);     /*     1     3     */
    root.left.left = newNode(4);     /* / \ \ */
    root.left.right = newNode(6);     /* 4     6 8 */
    root.right.right = newNode(8); /*     /     */
    root.left.right.left = newNode(5);/*     5     */
 
    System.out.println("Level having maximum number of Nodes : " + maxNodeLevel(root));
}
}


Python3




# Python3 implementation to find the
# level having Maximum number of Nodes
 
# Importing Queue
from queue import Queue
 
# Helper class that allocates a new
# node with the given data and None
# left and right pointers.
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# function to find the level
# having Maximum number of Nodes
def maxNodeLevel(root):
    if (root == None):
        return -1
 
    q = Queue()
    q.put(root)
 
    # Current level
    level = 0
 
    # Maximum Nodes at same level
    Max = -999999999999
 
    # Level having Maximum Nodes
    level_no = 0
 
    while (1):
         
        # Count Nodes in a level
        NodeCount = q.qsize()
 
        if (NodeCount == 0):
            break
 
        # If it is Maximum till now
        # Update level_no to current level
        if (NodeCount > Max):
            Max = NodeCount
            level_no = level
 
        # Pop complete current level
        while (NodeCount > 0):
            Node = q.queue[0]
            q.get()
            if (Node.left != None):
                q.put(Node.left)
            if (Node.right != None):
                q.put(Node.right)
            NodeCount -= 1
 
        # Increment for next level
        level += 1
 
    return level_no
 
# Driver Code
if __name__ == '__main__':
     
    # binary tree formation
    root = newNode(2)     #     2    
    root.left     = newNode(1)     #     / \
    root.right     = newNode(3)     #     1     3    
    root.left.left = newNode(4)     # / \ \
    root.left.right = newNode(6)     # 4     6 8
    root.right.right = newNode(8) #     /    
    root.left.right.left = newNode(5)#     5    
 
    print("Level having Maximum number of Nodes : ",
                                 maxNodeLevel(root))
 
# This code is contributed by Pranchalk


C#




using System;
using System.Collections.Generic;
 
// C# implementation to find the level 
// having maximum number of Nodes 
public class GfG
{
 
/* A binary tree Node has data, pointer 
to left child and a pointer to right 
child */
public class Node
{
    public int data;
    public Node left;
    public Node right;
}
 
/* Helper function that allocates a new node with the 
given data and NULL left and right pointers. */
public static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    return (node);
}
 
// function to find the level 
// having maximum number of Nodes 
public static int maxNodeLevel(Node root)
{
    if (root == null)
    {
        return -1;
    }
 
    LinkedList<Node> q = new LinkedList<Node> ();
    q.AddLast(root);
 
    // Current level 
    int level = 0;
 
    // Maximum Nodes at same level 
    int max = int.MinValue;
 
    // Level having maximum Nodes 
    int level_no = 0;
 
    while (true)
    {
        // Count Nodes in a level 
        int NodeCount = q.Count;
 
        if (NodeCount == 0)
        {
            break;
        }
 
        // If it is maximum till now 
        // Update level_no to current level 
        if (NodeCount > max)
        {
            max = NodeCount;
            level_no = level;
        }
 
        // Pop complete current level 
        while (NodeCount > 0)
        {
            Node Node = q.First.Value;
            q.RemoveFirst();
            if (Node.left != null)
            {
                q.AddLast(Node.left);
            }
            if (Node.right != null)
            {
                q.AddLast(Node.right);
            }
            NodeCount--;
        }
 
        // Increment for next level 
        level++;
    }
 
    return level_no;
}
 
// Driver program to test above 
public static void Main(string[] args)
{
    // binary tree formation 
     Node root = newNode(2); //  2
    root.left = newNode(1); //  / \
    root.right = newNode(3); //  1   3
    root.left.left = newNode(4); // / \ \
    root.left.right = newNode(6); // 4    6 8
    root.right.right = newNode(8); //    /
    root.left.right.left = newNode(5); //     5
 
    Console.WriteLine("Level having maximum number of Nodes : " + maxNodeLevel(root));
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
 
// Javascript implementation to find the level 
// having maximum number of Nodes 
 
/* A binary tree Node has data, pointer 
to left child and a pointer to right 
child */
class Node
{
    constructor()
    {
        this.data = 0;
        this.left = null;
        this.right = null;
    }
}
 
/* Helper function that allocates a new node with the 
given data and NULL left and right pointers. */
function newNode(data)
{
    var node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    return (node);
}
 
// function to find the level 
// having maximum number of Nodes 
function maxNodeLevel(root)
{
    if (root == null)
    {
        return -1;
    }
 
    var q = [];
    q.push(root);
 
    // Current level 
    var level = 0;
 
    // Maximum Nodes at same level 
    var max = -1000000000;
 
    // Level having maximum Nodes 
    var level_no = 0;
 
    while (true)
    {
        // length Nodes in a level 
        var NodeCount = q.length;
 
        if (NodeCount == 0)
        {
            break;
        }
 
        // If it is maximum till now 
        // Update level_no to current level 
        if (NodeCount > max)
        {
            max = NodeCount;
            level_no = level;
        }
 
        // Pop complete current level 
        while (NodeCount > 0)
        {
            var Node = q[0];
            q.shift();
            if (Node.left != null)
            {
                q.push(Node.left);
            }
            if (Node.right != null)
            {
                q.push(Node.right);
            }
            NodeCount--;
        }
 
        // Increment for next level 
        level++;
    }
 
    return level_no;
}
 
// Driver program to test above 
// binary tree formation 
var root = newNode(2); //  2
root.left = newNode(1); //  / \
root.right = newNode(3); //  1   3
root.left.left = newNode(4); // / \ \
root.left.right = newNode(6); // 4    6 8
root.right.right = newNode(8); //    /
root.left.right.left = newNode(5); //     5
document.write("Level having maximum number of Nodes : " + maxNodeLevel(root));
 
// This code is contributed by famously.
</script>


Output

Level having maximum number of Nodes : 2

Time Complexity: O(n), In BFS traversal every node is visited only once, So Time Complexity is O(n).
Auxiliary Space: O(n), The space is required to store the nodes in a queue.

An approach using DFS:

Iterate over the tree and for every nodes in the tree, count the frequency of nodes at particular height or depth.

  • Create a map for counting the frequency of nodes at a particular height or depth.
  • Iterate over the tree
  • Increment the count of the number of nodes at a particular depth for every node.
  • Iterate over the map and find the level that has the maximum number of nodes.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// C++ implementation to find the level
// having maximum number of Nodes
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree Node has data, pointer
   to left child and a pointer to right
   child */
struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
};
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return(node);
}
 
 
void dfs(Node* root,unordered_map<int, int> &unmap;, int depth){
    if(root == NULL) return;
     
    // Increment the count of nodes at depth in map
    unmap[depth]++;
     
    dfs(root->left,unmap, depth + 1);
    dfs(root->right, unmap, depth + 1);
}
 
int maxNodeLevel(Node *root)
{
    unordered_map<int, int> unmap;
    dfs(root, unmap, 0);
    int maxx = INT_MIN, result;
     
    for(auto it : unmap){
        if(it.second > maxx){
            result = it.first;
            maxx = it.second;
        }
        else if(it.second == maxx){
            result = min(result, it.first);
        }
    }
     
    return result;
}
 
// Driver program to test above
int main()
{
    // binary tree formation
    struct Node *root = newNode(2);      /*        2      */
    root->left        = newNode(1);      /*      /   \    */
    root->right       = newNode(3);      /*     1     3      */
    root->left->left  = newNode(4);      /*   /   \    \  */
    root->left->right = newNode(6);      /*  4     6    8 */
    root->right->right  = newNode(8);    /*       /       */
    root->left->right->left = newNode(5);/*      5        */
 
    printf("Level having maximum number of Nodes : %d",
            maxNodeLevel(root));
    return 0;
}
 
// This code is contributed by hkdass001


Java




// Java implementation to find the level having
// maximum number of nodes
import java.util.*;
class GFG{
    /* A binary tree Node has data, pointer
    to left child and a pointer to right
    child */
    static class Node{
        int data;
        Node left;
        Node right;
    }
     
    /* Helper function that allocates a new node with the
    given data and NULL left and right pointers. */  
    static Node newNode(int data){
        Node node = new Node();
        node.data = data;
        node.left = null;
        node.right = null;
        return node;
    }
     
    static void dfs(Node root, Map<Integer, Integer> unmap, int depth){
        if(root == null) return;
         
        // Increment the count of nodes at depth in map
        if(unmap.containsKey(depth)){
            unmap.put(depth, unmap.get(depth)+1);
        }else{
            unmap.put(depth, 1);
        }
        // unmap.put(depth, unmap.get(depth) + 1);
        dfs(root.left, unmap, depth+1);
        dfs(root.right, unmap, depth+1);
    }
     
    // function to find the level
    // having maximum number of Nodes
    static int maxNodeLevel(Node root){
        Map<Integer, Integer> unmap = new HashMap<Integer, Integer>();
        dfs(root, unmap, 0);
        int maxx = Integer.MIN_VALUE;
        int result = 0;
         
        for(Integer i : unmap.keySet()){
            if(unmap.get(i) > maxx){
                result = i;
                maxx = unmap.get(i);
            }
            else if(unmap.get(i) == maxx){
                result = Math.min(result, i);
            }
            // System.out.println(i + " -> " + unmap.get(i));
        }
        return result;
    }
     
    // Driver program to test above
    public static void main(String[] args)
    {
        // binary tree formation
        Node root = newNode(2);           /*        2         */
        root.left        = newNode(1);    /*      /   \       */
        root.right       = newNode(3);    /*     1     3      */
        root.left.left  = newNode(4);     /*   /   \    \     */
        root.left.right = newNode(6);     /*  4     6    8    */
        root.right.right  = newNode(8);   /*       /          */
        root.left.right.left = newNode(5);/*      5           */
      
        System.out.println("Level having maximum number of Nodes : " + maxNodeLevel(root));
    }
}
 
// This code is contributed by Kirti Agarwal


Python3




# Python implementation to find the level
# having maximum number of Nodes
 
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
def dfs(root, unmap, depth):
    if root is None:
        return
    # Initialize the count of nodes at depth in map to 0
    unmap[depth] = unmap.get(depth, 0) + 1
    dfs(root.left, unmap, depth + 1)
    dfs(root.right, unmap, depth + 1)
 
 
def maxNodeLevel(root):
    unmap = {}
    dfs(root, unmap, 0)
    maxx = float('-inf')
    result = None
    for k, v in unmap.items():
        if v > maxx:
            result = k
            maxx = v
        elif v == maxx:
            result = min(result, k)
    return result
 
# Driver program to test above
if __name__ == "__main__":
    # binary tree formation
    root = Node(2)                       #   2
    root.left = Node(1)                  #  / \
    root.right = Node(3)                 # 1   3
    root.left.left = Node(4)            # / \  \
    root.left.right = Node(6)          # 4   6  8
    root.right.right = Node(8)            # /
    root.left.right.left = Node(5)       # 5
 
    print("Level having maximum number of Nodes:", maxNodeLevel(root))


Javascript




// JavaScript implementation to find the level
// having maximum number of nodes
 
// A binary tree node has data, pointer
// to left child and a pointer to right child
class Node{
    constructor(data){
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// Helper Function that allocated a new node with the
// given data and null left and right pointers
function newNode(data){
    let node = new Node(data);
    return node;
}
 
function dfs(root, unmap, depth){
    if(root == null) return;
     
    // Increment the count of nodes at depth in map
    if(unmap.has(depth))
        unmap.set(depth, unmap.get(depth)+1);
    else
        unmap.set(depth, 1);
    dfs(root.left, unmap, depth+1);
    dfs(root.right, unmap, depth+1);
}
 
function maxNodeLevel(root){
    let unmap = new Map();
    dfs(root, unmap, 0);
    let maxx = Number.MIN_VALUE;
    let result;
     
    unmap.forEach(function(value, key){
        if(value > maxx){
            result = key;
            maxx = value;
        }else if(value == maxx){
            result = Math.min(result, key);
        }
    })
     
    return result;
}
 
// Driver program to test above
// binary tree formation
let root = newNode(2);            /*        2         */
root.left        = newNode(1);    /*      /   \       */
root.right       = newNode(3);    /*     1     3      */
root.left.left  = newNode(4);     /*   /   \    \     */
root.left.right = newNode(6);     /*  4     6    8    */
root.right.right  = newNode(8);   /*       /          */
root.left.right.left = newNode(5);/*      5           */
 
console.log("Level having maximum number of Nodes : " + maxNodeLevel(root));
 
// This code is contributed by Yash Agarwal


C#




using System;
using System.Collections.Generic;
 
public class GFG
{
    // A binary tree Node has data, pointer to left child and a pointer to right child
    public class Node
    {
        public int data;
        public Node left;
        public Node right;
    }
 
    // Helper function that allocates a new node with the given data and NULL left and right pointers.
    public static Node NewNode(int data)
    {
        Node node = new Node();
        node.data = data;
        node.left = null;
        node.right = null;
        return node;
    }
 
    public static void Dfs(Node root, Dictionary<int, int> unmap, int depth)
    {
        if (root == null)
        {
            return;
        }
 
        // Increment the count of nodes at depth in map
        if (unmap.ContainsKey(depth))
        {
            unmap[depth]++;
        }
        else
        {
            unmap.Add(depth, 1);
        }
 
        Dfs(root.left, unmap, depth + 1);
        Dfs(root.right, unmap, depth + 1);
    }
 
    // Function to find the level having maximum number of nodes
    public static int MaxNodeLevel(Node root)
    {
        Dictionary<int, int> unmap = new Dictionary<int, int>();
        Dfs(root, unmap, 0);
        int maxx = int.MinValue;
        int result = 0;
 
        foreach (int i in unmap.Keys)
        {
            if (unmap[i] > maxx)
            {
                result = i;
                maxx = unmap[i];
            }
            else if (unmap[i] == maxx)
            {
                result = Math.Min(result, i);
            }
        }
 
        return result;
    }
 
    // Driver program to test above
    public static void Main(string[] args)
    {
        // binary tree formation
        Node root = NewNode(2);           /*        2         */
        root.left = NewNode(1);           /*      /   \       */
        root.right = NewNode(3);          /*     1     3      */
        root.left.left = NewNode(4);      /*   /   \    \     */
        root.left.right = NewNode(6);     /*  4     6    8    */
        root.right.right = NewNode(8);    /*       /          */
        root.left.right.left = NewNode(5);/*      5           */
 
        Console.WriteLine("Level having maximum number of Nodes: " + MaxNodeLevel(root));
    }
}


Output

Level having maximum number of Nodes : 2

Time Complexity: O(n), where n is the number of nodes in the given tree.
Auxiliary Space: O(h), where h is the height of the tree, this space is due to the recursion call stack.

 



Previous Article
Next Article

Similar Reads

Print the nodes corresponding to the level value for each level of a Binary Tree
Given a Binary Tree, the task for each level L is to print the Lth node of the tree. If the Lth node is not present for any level, print -1. Note: Consider the root node to be at the level 1 of the binary tree. Examples: Input: Below is the given Tree: Output:Level 1: 1Level 2: 3 Level 3: 6Level 4: 11Explanation:For the first level, the 1st node is
15 min read
Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
Given a Binary Tree, the task is for each level is to print the total number of nodes from all lower levels which are less than or equal to every node present at that level. Examples: Input: Below is the given tree: 4 / \ 3 5 / \ / \ 10 2 3 1 Output: 4 3 0Explanation:Nodes in level 1 has 4 nodes as (3) in level 2 and (2, 3, 1) in level 3. Nodes in
11 min read
Difference between sums of odd level and even level nodes in an N-ary Tree
Given an N-ary Tree rooted at 1, the task is to find the difference between the sum of nodes at the odd level and the sum of nodes at even level. Examples: Input: 4 / | \ 2 3 -5 / \ / \ -1 3 -2 6Output: 10Explanation:Sum of nodes at even levels = 2 + 3 + (-5) = 0Sum of nodes at odd levels = 4 + (-1) + 3 + (-2) + 6 = 10Hence, the required difference
9 min read
Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
Given a Binary Search Tree, the task is to print the nodes of the BST in the following order: If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N - 1, and so on.The top-level order (1, 2, â€Ķ) nodes are printed from left to right, while the bottom level order (N, N-1, ...) nodes are printed f
15+ min read
Modify a Binary Tree by adding a level of nodes with given value at a specified level
Given a Binary Tree consisting of N nodes and two integers K and L, the task is to add one row of nodes of value K at the Lth level, such that the orientation of the original tree remains unchanged. Examples: Input: K = 1, L = 2 Output:11 12 34 5 6 Explanation:Below is the tree after inserting node with value 1 in the K(= 2) th level. Input: K = 1,
15+ min read
Calculate sum of all nodes present in a level for each level of a Tree
Given a Generic Tree consisting of N nodes (rooted at 0) where each node is associated with a value, the task for each level of the Tree is to find the sum of all node values present at that level of the tree. Examples: Input: node_number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, node_values = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 } Output: Sum of level 0 = 2S
14 min read
Connect Nodes at same Level (Level Order Traversal)
Write a function to connect all the adjacent nodes at the same level in a binary tree. Example: Input Tree A / \ B C / \ \ D E F Output Tree A--->NULL / \ B-->C-->NULL / \ \ D-->E-->F-->NULL We have already discussed O(n^2) time and O approach in Connect nodes at same level as morris traversal in worst case can be O(n) and calling
9 min read
Difference between sums of odd level and even level nodes of a Binary Tree
Given a Binary Tree, find the difference between the sum of nodes at odd level and the sum of nodes at even level. Consider root as level 1, left and right children of root as level 2 and so on. For example, in the following tree, sum of nodes at odd level is (5 + 1 + 4 + 8) which is 18. And sum of nodes at even level is (2 + 6 + 3 + 7 + 9) which i
15+ min read
Level with maximum number of nodes using DFS in a N-ary tree
Given a N-ary tree, the task is to print the level with the maximum number of nodes. Examples: Input : For example, consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4 Output : Level-3 and Level-4 Approach: Insert all the connecting nodes to a 2-D vector tree.Run a DFS on the tree such that height[n
10 min read
Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
Given a perfect binary tree of N nodes, with nodes having values from 1 to N as depicted in the image below and Q queries where every query consists of two integers L and X. The task is to find the maximum possible value of X XOR Y where Y can be any node at level L. Examples: Input: Q[] = {{2, 5}, {3, 15}} Output: 7 11 1st Query: Level 2 has numbe
8 min read
Print levels with odd number of nodes and even number of nodes
Given an N-ary tree, print all the levels with odd and even numbers of nodes in it. Examples: For example consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2Note: The level numbers starts from 1. That is, the r
15+ min read
Count the number of nodes at given level in a tree using BFS.
Given a tree represented as an undirected graph. Count the number of nodes at a given level l. It may be assumed that vertex 0 is the root of the tree. Examples: Input : 7 0 1 0 2 1 3 1 4 1 5 2 6 2 Output : 4 Input : 6 0 1 0 2 1 3 2 4 2 5 2 Output : 3 BFS is a traversing algorithm that starts traversing from a selected node (source or starting node
9 min read
Count the number of nodes at a given level in a tree using DFS
Given an integer l and a tree represented as an undirected graph rooted at vertex 0. The task is to print the number of nodes present at level l. Examples:  Input: l = 2   Output: 4  We have already discussed the BFS approach, in this post we will solve it using DFS. Approach: The idea is to traverse the graph in a DFS manner. Take two variables, c
8 min read
Minimum value to be added at each level in Binary Tree to make all level sum equal
Given a binary tree, the task is to find all minimum values greater than or equal to zero, that should be added at each level to make the sum at each level equal. Examples: Input: 1 / \ 2 3 / \ 4 5 Output: 8 4 0Explanation: Initial sum at each level is {1, 5, 9}. To make all levels sum equal minimum values to be added are {8, 4, 0}. So the final su
9 min read
Difference between odd level and even level leaf sum in given Binary Tree
Given a Binary Tree, the task is to find the difference of the sum of leaf nodes at the odd level and even level of the given tree. Examples: Input: Output: -12Explanation: Following are the operations performed to get the result.odd_level_sum = 0, even_level_sum = 0Level 1: No leaf node, so odd_level_sum = 0Level 2: No leaf node, so even_level_sum
13 min read
Minimum number of Nodes to be removed such that no subtree has more than K nodes
Given a tree with N nodes value from 1 to N and (N - 1) Edges and a number K, the task is to remove the minimum number of nodes from the tree such that every subtree will have at most K nodes. Removing Nodes will remove the edges from that nodes to all the other connected nodes. Examples: Input: N = 10, K = 3, Below is the graph: Output: Number of
9 min read
Minimum number of nodes to be selected to light up all the edges of the tree (Select Nodes)
Given N nodes of a tree and a list of edges. Find the minimum number of nodes to be selected to light up all the edges of the tree. An edge lights up when at least one node at the end of the edge is selected. Example: Input: N = 6, edges[] = {(1,2), (1,3), (2,4), (3,5), (3,6)}Output: 2Explanation: Selecting nodes 2 and 3 lights up all the edges. In
10 min read
Print nodes between two given level numbers of a binary tree
Given a binary tree and two level numbers 'low' and 'high', print nodes from level low to level high. For example consider the binary tree given in below diagram. Input: Root of below tree, low = 2, high = 4 Output: 8 22 4 12 10 14 A Simple Method is to first write a recursive function that prints nodes of a given level number. Then call a recursiv
10 min read
Print odd positioned nodes of odd levels in level order of the given binary tree
Given a binary tree, the task is to print the odd positioned nodes of odd levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output: 3 9 Input: 2 / \ 4 15 / / 45 17 Output: 15 Prerequi
8 min read
Print Leaf Nodes at a given Level
Given a Binary tree, print all the leaf nodes of a Binary tree at a given level L. Examples: Input: 1 / \ 2 3 / / \ 4 5 6 level = 3 Output: 4 5 6 Input: 7 / \ 2 3 / \ \ 4 9 10 / 6 level = 3 Output: 4 9 Approach: Recursively traverse the tree in a level order manner. If the current level is the same as the given level, then check whether the current
5 min read
Count nodes with two children at level L in a Binary Tree
Given a Binary tree, the task is to count the number of nodes with two children at a given level L. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 L = 2 Output: 1 Input: 20 / \ 8 22 / \ / \ 5 3 4 25 / \ / \ \ 1 10 2 14 6 L = 3 Output: 2 Approach: Initialize a variable count = 0. Recursively traverse the tree in a level order manner. If the curr
13 min read
Recursive Program to Print extreme nodes of each level of Binary Tree in alternate order
Given a binary tree, the task is to print nodes of extreme corners of each level but in alternate order.Examples: Input : 1 / \ 2 3 / / \ 4 5 6 / / \ 7 8 9 Output : 1 2 6 7 Print the rightmost node at 1st level: 1 Print the leftmost node at 2nd level: 2 Print the rightmost node at 3rd level: 6 Print the leftmost node at 4th level: 7 Other possible
14 min read
Print even positioned nodes of even levels in level order of the given binary tree
Given a binary tree, print even positioned nodes of even level in level order traversal. The root is considered at level 0, and the left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 1 4 6 9 Input: 2 / \ 4 15 / / 45 17 Output: 2 45 Approach: To print nodes level by leve
8 min read
Difference between sums of odd position and even position nodes for each level of a Binary Tree
Given a Binary Tree, the task is to find the absolute difference between the sums of odd and even positioned nodes. A node is said to be odd and even positioned if its position in the current level is odd and even respectively. Note that the first element of each row is considered as odd positioned.Examples: Input: 5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9
8 min read
Print all the nodes except the leftmost node in every level of the given binary tree
Given a binary tree, the task is to print all the nodes except the leftmost in every level of the tree. The root is considered at level 0, and left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 3 5 6 8 10 Input: 1 / \ 2 3 \ \ 4 5 Output: 3 5 Approach: To print nodes lev
8 min read
Print even positioned nodes of odd levels in level order of the given binary tree
Given a binary tree, the task is to print the even positioned nodes of odd levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output: 2 8 Input: 2 / \ 4 15 / / 45 17 Output: 4 Prerequi
8 min read
Print odd positioned nodes of even levels in level order of the given binary tree
Given a binary tree, the task is to print the odd positioned nodes of even levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output: 5 7 11 Input: 2 / \ 4 15 / / 45 17 Output: 17 Prer
8 min read
Print all nodes except rightmost node of every level of the Binary Tree
Given a binary tree, the task is to print all the nodes except the rightmost in every level of the tree. The root is considered at level 0, and rightmost node of any level is considered as a node at position 0.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 2 4 5 7 9 Input: 1 / \ 2 3 \ \ 4 5 Output: 2 4 Approach: To print nodes leve
7 min read
Product of nodes at k-th level in a tree represented as string using Recursion
Prerequisite: Product of nodes at k-th level in a tree represented as stringGiven an integer ‘K’ and a binary tree in string format. Every node of a tree has value in range from 0 to 9. We need to find product of elements at K-th level from the root. The root is at level 0.Note: Tree is given in the form: (node value(left subtree)(right subtree))Ex
5 min read
Article Tags :
Practice Tags :