C++ program to find level with maximum number of nodes














































C++ program to find level with maximum number of nodes



The code is to find the the level having maximum number of nodes.
Example:
   Input:
                          
Output:

      Level having maximum nodes : 2

Explanation:

          We consider the root to be level 0, and subsequently calculate the no of nodes in a level taking the help of a queue.

Program:
// C++ program to find level with maximum number of nodes #include <bits/stdc++.h> #include<iostream> using namespace std; // structure of a node, having data, and left and right child struct Node { int data; struct Node* left; struct Node* right; }; // function creating a new node 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 no of node int maxNodesLevel(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 = -1; // Level having maximum Nodes int levelNo = 0; for(;;) //infinite loop { // 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; levelNo = 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 levelNo; } // main function int main() { // creation of binary tree struct Node *root = newNode(6); root->left = newNode(4); root->right = newNode(15); root->left->left = newNode(3); root->left->right = newNode(6); root->left->right->left = newNode(5); root->right->left = newNode(10); root->right->left->left = newNode(9); cout<<"Level having maximum no of nodes "<<maxNodesLevel(root); return 0; }


More Articles of Satyaki Majumder:

Name Views Likes
C++ program to find level with maximum number of nodes 243 22

Comments