Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node.
Examples:
Input:
Output: 2 Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which has 2 edges.
Input:
Output: 3 Explanation: The longest path from the root (node 1) to a leaf node 6 with 3 edge.
[Approach 1] Using Recursion - O(n) Time and O(h) Space
The idea is to recursively calculate the height of the left and the right subtrees of a node and then find height to the node as max of the heights of two children plus 1.
Algorithm:
If the tree is empty, return -1.
Otherwise, do the following:
Get the height of the left subtree recursively, i.e., call height(node->left).
Get the height of the right subtree recursively, i.e., call height(node->right).
Compute the maximum of the heights of the left and right subtrees and add 1 to it for the current node.
height = max(height of left subtree, height of right subtree) + 1.
Return the height.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Returns height which is the number of edges// along the longest path from the root node down // to the farthest leaf node.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>structNode{intdata;structNode*left;structNode*right;};// Returns "height" which is the number of edges // along the longest path from the root node down // to the farthest leaf node.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
classNode{intdata;Nodeleft,right;Node(intval){data=val;left=null;right=null;}}classGfG{// Returns height which is the number of edges// along the longest path from the root node down // to the farthest leaf node.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
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Returns height which is the number of edges# along the longest path from the root node down # to the farthest leaf node.defheight(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;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=null;right=null;}}classGfG{// Returns height which is the number of edges// along the longest path from the root node down // to the farthest leaf node.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
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Returns height which is the number of edges// along the longest path from the root node down // to the farthest leaf node.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));
[Approach 2] Level Order Traversal - O(n) Time and O(n) Space
If we take a closer look at the breadth first traversal, we can notice that after we process the last node of the current level, the queue contains all the nodes of next level. This is true from the root (or first level) So we get the size of the queue in a loop to count the nodes of every level.
Algorithm:
Initialize an empty queueq to store nodes of the tree and a variable depth to keep track of the number of levels.
Push the root node into the queue q.
While the queue is not empty:
Store the number of nodes at the current level as levelSize (the size of the queue).
For each node in the current level (loop from 0 to levelSize):
Dequeue the front element from the queue (i.e., process the node).
If the node has a left child, enqueue it.
If the node has a right child, enqueue it.
After processing all nodes at the current level, increment the depth.
Returndepth - 1 as the number of edges encountered will be one less than number of nodes.
C++
#include<iostream>#include<queue>usingnamespacestd;classNode{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();if(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;}
Java
importjava.util.LinkedList;importjava.util.Queue;classNode{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));}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to find the height of the treedefheight(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;classNode{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
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to find the height of the treefunctionheight(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;}// 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));
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.