#include<iostream>#include<climits>#include<algorithm>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};intmaxLevel(Node*root){if(root==nullptr)return0;if(root->left==nullptrandroot->right==nullptr)return1;// no child nodes indicate base caseintleft,right;if(root->left!=nullptr)left=maxLevel(root->left);// finding depth of left sub treeelseleft=INT_MIN;if(root->right!=nullptr)right=maxLevel(root->right);// finding depth of right sub treeelseright=INT_MIN;return1+max(left,right);}intmain(){// Representation of the input tree:// 10// / \ // 20 30// \ \ // 40 60// /// 2Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->right=newNode(40);root->right->right=newNode(60);root->right->right->left=newNode(2);cout<<maxLevel(root);return0;}
C
#include<limits.h>#include<stdio.h>#include<stdlib.h>typedefstructNode{intdata;structNode*left;structNode*right;}Node;Node*createNode(intval){Node*newNode=(Node*)malloc(sizeof(Node));newNode->data=val;newNode->left=newNode->right=NULL;returnnewNode;}intmaxLevel(Node*root){if(root==NULL)return0;if(root->left==NULL&&root->right==NULL)return1;// no child nodes indicate base caseintleft=INT_MIN,right=INT_MIN;if(root->left!=NULL)left=maxLevel(root->left);// finding depth of left sub treeif(root->right!=NULL)right=maxLevel(root->right);// finding depth of right sub treereturn1+(left>right?left:right);}intmain(){// Representation of the input tree:// 10// / \ // 20 30// \ \ // 40 60// /// 2Node*root=createNode(10);root->left=createNode(20);root->right=createNode(30);root->left->right=createNode(40);root->right->right=createNode(60);root->right->right->left=createNode(2);printf("%d",maxLevel(root));return0;}
Java
importjava.util.Arrays;classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=right=null;}}publicclassGFG{staticintmaxLevel(Noderoot){if(root==null)return0;if(root.left==null&&root.right==null)return1;// no child nodes indicate base caseintleft=Integer.MIN_VALUE,right=Integer.MIN_VALUE;if(root.left!=null)left=maxLevel(root.left);// finding depth of left sub treeif(root.right!=null)right=maxLevel(root.right);// finding depth of right sub treereturn1+Math.max(left,right);}publicstaticvoidmain(String[]args){// Representation of the input tree:// 10// / \// 20 30// \ \// 40 60// /// 2Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.right=newNode(40);root.right.right=newNode(60);root.right.right.left=newNode(2);System.out.println(maxLevel(root));}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefmaxLevel(root):ifrootisNone:return0ifroot.leftisNoneandroot.rightisNone:return1# no child nodes indicate base caseleft=float('-inf')right=float('-inf')ifroot.leftisnotNone:left=maxLevel(root.left)# finding depth of left sub treeifroot.rightisnotNone:right=maxLevel(root.right)# finding depth of right sub treereturn1+max(left,right)if__name__=='__main__':# Representation of the input tree:# 10# / \# 20 30# \ \# 40 60# /# 2root=Node(10)root.left=Node(20)root.right=Node(30)root.left.right=Node(40)root.right.right=Node(60)root.right.right.left=Node(2)print(maxLevel(root))
C#
usingSystem;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}publicclassGFG{publicstaticintmaxLevel(Noderoot){if(root==null)return0;if(root.left==null&&root.right==null)return1;// no child nodes indicate base caseintleft=int.MinValue,right=int.MinValue;if(root.left!=null)left=maxLevel(root.left);// finding depth of left sub treeif(root.right!=null)right=maxLevel(root.right);// finding depth of right sub treereturn1+Math.Max(left,right);}publicstaticvoidMain(){// Representation of the input tree:// 10// / \// 20 30// \ \// 40 60// /// 2Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.right=newNode(40);root.right.right=newNode(60);root.right.right.left=newNode(2);Console.WriteLine(maxLevel(root));}}
JavaScript
classNode{constructor(val){this.data=val;this.left=this.right=null;}}functionmaxLevel(root){if(root===null)return0;if(root.left===null&&root.right===null)return1;// no child nodes indicate base caseletleft=Number.NEGATIVE_INFINITY,right=Number.NEGATIVE_INFINITY;if(root.left!==null)left=maxLevel(root.left);// finding depth of left sub treeif(root.right!==null)right=maxLevel(root.right);// finding depth of right sub treereturn1+Math.max(left,right);}// Driver Code// Representation of the input tree:// 10// / \// 20 30// \ \// 40 60// /// 2letroot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.right=newNode(40);root.right.right=newNode(60);root.right.right.left=newNode(2);console.log(maxLevel(root));
Output
4
Level Order Traversal - O(n) Time and O(n) Space
The idea is to traverse the tree level by level using a queue. At each step, we process all nodes present at the current level and add their children to the queue.
After processing all nodes of a level, we increment the level counter.
When the queue becomes empty, the counter represents the maximum level of the binary tree.
Let us understand with an example: Input: root = [10, 20, 30, N, 40, N, 60, N, N, 2, N, N, N]
The tree is processed level by level:
Level 1: 10
Level 2: 20, 30
Level 3: 40, 60
Level 4: 2
After processing all four levels, the queue becomes empty. Therefore, the maximum level is 4.
C++
#include<iostream>#include<queue>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};intmaxLevel(Node*root){if(root==nullptr)return0;// Initialize a queue for level order traversal.queue<Node*>q;q.push(root);intlevel=0;// Traverse the tree level by level.while(!q.empty()){intlevelSize=q.size();// Process all nodes at the current level.for(inti=0;i<levelSize;i++){Node*curr=q.front();q.pop();// Add the left child to the queue.if(curr->left!=nullptr)q.push(curr->left);// Add the right child to the queue.if(curr->right!=nullptr)q.push(curr->right);}// Move to the next level.level++;}returnlevel;}intmain(){// Representation of the input tree:// 10// / \ // 20 30// \ \ // 40 60// /// 2Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->right=newNode(40);root->right->right=newNode(60);root->right->right->left=newNode(2);cout<<maxLevel(root);return0;}
C
#include<stdbool.h>#include<stdio.h>#include<stdlib.h>typedefstructNode{intdata;structNode*left;structNode*right;}Node;Node*newNode(intdata){Node*node=(Node*)malloc(sizeof(Node));node->data=data;node->left=NULL;node->right=NULL;returnnode;}typedefstructQueue{Node**items;intfront,rear,size,capacity;}Queue;Queue*createQueue(intcapacity){Queue*queue=(Queue*)malloc(sizeof(Queue));queue->items=(Node**)malloc(sizeof(Node*)*capacity);queue->front=0;queue->rear=-1;queue->size=0;queue->capacity=capacity;returnqueue;}boolisEmpty(Queue*queue){returnqueue->size==0;}voidenqueue(Queue*queue,Node*node){queue->rear=(queue->rear+1)%queue->capacity;queue->items[queue->rear]=node;queue->size++;}Node*dequeue(Queue*queue){Node*node=queue->items[queue->front];queue->front=(queue->front+1)%queue->capacity;queue->size--;returnnode;}intmaxLevel(Node*root){if(root==NULL)return0;Queue*queue=createQueue(100);enqueue(queue,root);intlevel=0;while(!isEmpty(queue)){intlevelSize=queue->size;for(inti=0;i<levelSize;i++){Node*curr=dequeue(queue);if(curr->left!=NULL)enqueue(queue,curr->left);if(curr->right!=NULL)enqueue(queue,curr->right);}level++;}free(queue->items);free(queue);returnlevel;}intmain(){// Representation of the input tree:// 10// / \ // 20 30// \ \ // 40 60// /// 2Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->right=newNode(40);root->right->right=newNode(60);root->right->right->left=newNode(2);printf("%d",maxLevel(root));return0;}
Java
importjava.util.*;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}publicclassGFG{publicstaticintmaxLevel(Noderoot){if(root==null)return0;Queue<Node>q=newLinkedList<>();q.add(root);intlevel=0;while(!q.isEmpty()){intlevelSize=q.size();for(inti=0;i<levelSize;i++){Nodecurr=q.poll();if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);}level++;}returnlevel;}publicstaticvoidmain(String[]args){// Representation of the input tree:// 10// / \// 20 30// \ \// 40 60// /// 2Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.right=newNode(40);root.right.right=newNode(60);root.right.right.left=newNode(2);System.out.println(maxLevel(root));}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefmaxLevel(root):ifrootisNone:return0q=deque([root])level=0whileq:levelSize=len(q)for_inrange(levelSize):curr=q.popleft()ifcurr.leftisnotNone:q.append(curr.left)ifcurr.rightisnotNone:q.append(curr.right)level+=1returnlevelif__name__=='__main__':# Representation of the input tree:# 10# / \# 20 30# \ \# 40 60# /# 2root=Node(10)root.left=Node(20)root.right=Node(30)root.left.right=Node(40)root.right.right=Node(60)root.right.right.left=Node(2)print(maxLevel(root))
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}publicclassGFG{publicstaticintmaxLevel(Noderoot){if(root==null)return0;// Initialize a queue for level order traversal.Queue<Node>q=newQueue<Node>();q.Enqueue(root);intlevel=0;// Traverse the tree level by level.while(q.Count>0){intlevelSize=q.Count;// Process all nodes at the current level.for(inti=0;i<levelSize;i++){Nodecurr=q.Dequeue();// Add the left child to the queue.if(curr.left!=null)q.Enqueue(curr.left);// Add the right child to the queue.if(curr.right!=null)q.Enqueue(curr.right);}// Move to the next level.level++;}returnlevel;}publicstaticvoidMain(){// Representation of the input tree:// 10// / \// 20 30// \ \// 40 60// /// 2Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.right=newNode(40);root.right.right=newNode(60);root.right.right.left=newNode(2);Console.WriteLine(maxLevel(root));}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionmaxLevel(root){if(root===null){return0;}// Initialize a queue for level order traversal.letq=[];q.push(root);letlevel=0;// Traverse the tree level by level.while(q.length>0){letlevelSize=q.length;// Process all nodes at the current level.for(leti=0;i<levelSize;i++){letcurr=q.shift();// Add the left child to the queue.if(curr.left!==null){q.push(curr.left);}// Add the right child to the queue.if(curr.right!==null){q.push(curr.right);}}// Move to the next level.level++;}returnlevel;}// Driver Code// Representation of the input tree:// 10// / \// 20 30// \ \// 40 60// /// 2letroot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.right=newNode(40);root.right.right=newNode(60);root.right.right.left=newNode(2);console.log(maxLevel(root));