Given theroot of abinary tree, find themaximum depthof the tree.
The maximum depth or height of the tree is thenumber of edgesin the tree from the root to the deepest node.
Examples:
Input:

Output: 2
Explanation:The longest path from the root node to deepest node has 2 edges.
Input:

Output: 3
Explanation:The longest path from the root (node 1) to deepest leaf (node 6) has 3 edges.
[Approach 1] Using Recursion
The idea is to recursively compute the height of the left and right subtrees for each node. The height of the current node is then calculated by1 + max(leftHeight, rightHeight). The recursion bottoms out when we reach to a null node, which contributes a height of 0.
C++#include<iostream>usingnamespacestd;// Node structureclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};intheight(Node*root){if(root==nullptr)return-1;// compute the height of left and right subtreesintlHeight=height(root->left);intrHeight=height(root->right);returnmax(lHeight,rHeight)+1;}intmain(){// Representation of the input tree:// 12// / \ // 8 18// / \ // 5 11Node*root=newNode(12);root->left=newNode(8);root->right=newNode(18);root->left->left=newNode(5);root->left->right=newNode(11);cout<<height(root);return0;}C#include<stdio.h>#include<stdlib.h>// Node structurestructNode{intdata;structNode*left;structNode*right;};intheight(structNode*root){if(root==NULL)return-1;// compute the height of left and right subtreesintlHeight=height(root->left);intrHeight=height(root->right);return(lHeight>rHeight?lHeight:rHeight)+1;}structNode*createNode(intval){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=val;node->left=NULL;node->right=NULL;returnnode;}intmain(){// Representation of the input tree:// 12// / \ // 8 18// / \ // 5 11structNode*root=createNode(12);root->left=createNode(8);root->right=createNode(18);root->left->left=createNode(5);root->left->right=createNode(11);printf("%d\n",height(root));return0;}Java// Node structureclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=null;right=null;}}classGfG{staticintheight(Noderoot){if(root==null)return-1;// compute the height of left and right subtreesintlHeight=height(root.left);intrHeight=height(root.right);returnMath.max(lHeight,rHeight)+1;}publicstaticvoidmain(String[]args){// Representation of the input tree:// 12// / \// 8 18// / \// 5 11Noderoot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);System.out.println(height(root));}}Python# Node structureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=Nonedefheight(root):ifrootisNone:return-1# compute the height of left and right subtreeslHeight=height(root.left)rHeight=height(root.right)returnmax(lHeight,rHeight)+1if__name__=="__main__":# Representation of the input tree:# 12# / \# 8 18# / \# 5 11root=Node(12)root.left=Node(8)root.right=Node(18)root.left.left=Node(5)root.left.right=Node(11)print(height(root))
C#usingSystem;// Node structureclassNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=null;right=null;}}classGfG{staticintheight(Noderoot){if(root==null)return-1;// compute the height of left and right subtreesintlHeight=height(root.left);intrHeight=height(root.right);returnMath.Max(lHeight,rHeight)+1;}staticvoidMain(string[]args){// Representation of the input tree:// 12// / \// 8 18// / \// 5 11Noderoot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);Console.WriteLine(height(root));}}JavaScript// Node structureclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionheight(root){if(root===null){return-1;}// compute the height of left and right subtreesletlHeight=height(root.left);letrHeight=height(root.right);returnMath.max(lHeight,rHeight)+1;}// Driver Code// Representation of the input tree:// 12// / \// 8 18// / \// 5 11letroot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);console.log(height(root));Time Complexity: O(n)
Space Complexity: O(n), Recursive stack space
[Approach 2] Level Order Traversal- O(n) Time and O(n) Space
In level order traversal (BFS), we process the tree level by level. At each step, we note the number of nodes in the current level, process exactly those nodes, and enqueue their children. After finishing each level, we increment the depth counter. By the time the queue is empty, the counter reflects the maximum depth or height of the tree.
C++#include<iostream>#include<queue>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intval){data=val;left=nullptr;right=nullptr;}};intheight(Node*root){if(!root)return0;// Initializing a queue to traverse// the tree level by levelqueue<Node*>q;q.push(root);intdepth=0;// Loop until the queue is emptywhile(!q.empty()){intlevelSize=q.size();// Traverse all nodes at the current levelfor(inti=0;i<levelSize;i++){Node*curr=q.front();q.pop();// enqueue their child nodesif(curr->left)q.push(curr->left);if(curr->right)q.push(curr->right);}// Increment depth after traversing each leveldepth++;}returndepth-1;}intmain(){// Representation of the input tree:// 12// / \ // 8 18// / \ // 5 11Node*root=newNode(12);root->left=newNode(8);root->right=newNode(18);root->left->left=newNode(5);root->left->right=newNode(11);cout<<height(root);return0;}C#include<stdio.h>#include<stdlib.h>// Node StructurestructNode{intdata;structNode*left,*right;}// Function to create a new nodeNode*newNode(intval){Node*node=(Node*)malloc(sizeof(Node));node->data=val;node->left=NULL;node->right=NULL;returnnode;}// Queue structurestructQueue{Node**arr;intfront,rear,size,capacity;}// Function to create a queueQueue*createQueue(intcapacity){Queue*q=(Queue*)malloc(sizeof(Queue));q->capacity=capacity;q->front=0;q->rear=0;q->size=0;q->arr=(Node**)malloc(capacity*sizeof(Node*));returnq;}intisEmpty(Queue*q){returnq->size==0;}voidenqueue(Queue*q,Node*node){if(q->size==q->capacity)return;q->arr[q->rear]=node;q->rear=(q->rear+1)%q->capacity;q->size++;}Node*dequeue(Queue*q){if(isEmpty(q))returnNULL;Node*node=q->arr[q->front];q->front=(q->front+1)%q->capacity;q->size--;returnnode;}intheight(Node*root){if(!root)return0;// Initializing a queue to traverse// the tree level by levelQueue*q=createQueue(100);enqueue(q,root);intdepth=0;// Loop until the queue is emptywhile(!isEmpty(q)){intlevelSize=q->size;// Traverse all nodes at the current levelfor(inti=0;i<levelSize;i++){Node*curr=dequeue(q);// enqueue their child nodesif(curr->left)enqueue(q,curr->left);if(curr->right)enqueue(q,curr->right);}// Increment depth after traversing each leveldepth++;}returndepth-1;}intmain(){// Representation of the input tree:// 12// / \ // 8 18// / \ // 5 11Node*root=newNode(12);root->left=newNode(8);root->right=newNode(18);root->left->left=newNode(5);root->left->right=newNode(11);printf("%d",height(root));return0;}Javaimportjava.util.LinkedList;importjava.util.Queue;// Node StructureclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=null;right=null;}}classGfG{staticintheight(Noderoot){if(root==null)return0;// Initializing a queue to traverse// the tree level by levelQueue<Node>q=newLinkedList<>();q.add(root);intdepth=0;// Loop until the queue is emptywhile(!q.isEmpty()){intlevelSize=q.size();// Traverse all nodes at the current levelfor(inti=0;i<levelSize;i++){Nodecurr=q.poll();if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);}// Increment height after traversing each leveldepth++;}returndepth-1;}publicstaticvoidmain(String[]args){// Representation of the input tree:// 12// / \// 8 18// / \// 5 11Noderoot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);System.out.println(height(root));}}Pythonfromcollectionsimportdeque# Node StructureclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=Nonedefheight(root):ifrootisNone:return0# Initializing a queue to traverse# the tree level by levelq=deque([root])depth=0# Loop until the queue is emptywhileq:levelSize=len(q)# Traverse all nodes at the current levelfor_inrange(levelSize):curr=q.popleft()ifcurr.left:q.append(curr.left)ifcurr.right:q.append(curr.right)# Increment depth after traversing each leveldepth+=1returndepth-1if__name__=="__main__":# Representation of the input tree:# 12# / \# 8 18# / \# 5 11root=Node(12)root.left=Node(8)root.right=Node(18)root.left.left=Node(5)root.left.right=Node(11)print(height(root))
C#usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{staticintheight(Noderoot){if(root==null){return0;}// Initializing a queue to traverse// the tree level by levelQueue<Node>q=newQueue<Node>();q.Enqueue(root);intdepth=0;// Loop until the queue is emptywhile(q.Count>0){intlevelSize=q.Count;// Traverse all nodes at the current levelfor(inti=0;i<levelSize;i++){Nodecurr=q.Dequeue();if(curr.left!=null){q.Enqueue(curr.left);}if(curr.right!=null){q.Enqueue(curr.right);}}// Increment depth after traversing// a leveldepth++;}returndepth-1;}staticvoidMain(string[]args){// Representation of the input tree:// 12// / \// 8 18// / \// 5 11Noderoot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);Console.WriteLine(height(root));}}JavaScript// Node StructureclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}functionheight(root){if(root===null){return0;}// Initializing a queue to traverse// the tree level by levelletqueue=[root];letdepth=0;// Loop until the queue is emptywhile(queue.length>0){letlevelSize=queue.length;// Traverse all nodes at the current levelfor(leti=0;i<levelSize;i++){letcurr=queue.shift();if(curr.left){queue.push(curr.left);}if(curr.right){queue.push(curr.right);}}// Increment depth after traversing a leveldepth++;}returndepth-1;}//Driver Code// Representation of the input tree:// 12// / \// 8 18// / \// 5 11letroot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);console.log(height(root));
Height of a Binary Tree

Maximum Depth or Height of Binary Tree
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem