Maximum Depth or Height of Binary Tree
Last Updated :
27 Sep, 2024
Given a binary tree, the task is to find the maximum depth or height of the tree. The height of the tree is the number of vertices in the tree from the root to the deepest node.
Examples:
Example 1: The height of the below binary tree is 3.

Example 2: The height of the below binary tree is 4

[Expected Approach – 1] Using Recursion – O(n) Time and O(n) Space
The idea is to recursively calculate the height of the left and the right subtrees of a node and assign height to the node as max of the heights of two children plus 1.
Follow the steps below to solve the problem:
- If the tree is empty then return 0.
- Otherwise, do the following
- Get the max depth of the left subtree recursively i.e. call maxDepth( node->left).
- Get the max depth of the right subtree recursively i.e. call maxDepth( node->right).
- Get the max of max depths of left and right subtrees and add 1 to it for the current node.
- maxDepth = max(maxDepth of left subtree, max depth of right subtree) + 1.
- Return maxDepth.
Below is the Implementation of the above approach:
C++
// C++ program to find the maximum depth of a binary
// tree using depth-first search (DFS) approach.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left;
Node *right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
// Returns "maxDepth" which is the number of nodes
// along the longest path from the root node down
// to the farthest leaf node.
int maxDepth(Node *node) {
if (node == nullptr)
return 0;
// compute the depth of left and right subtrees
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
return max(lDepth, rDepth) + 1;
}
int main() {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
cout << maxDepth(root);
return 0;
}
C
// C program to find the maximum depth of a binary
// tree using depth-first search (DFS) approach.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Returns "maxDepth" which is the number of nodes
// along the longest path from the root node down
// to the farthest leaf node.
int maxDepth(struct Node* node) {
if (node == NULL)
return 0;
// compute the depth of left and right subtrees
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
return (lDepth > rDepth ? lDepth : rDepth) + 1;
}
struct Node* createNode(int val) {
struct Node* node
= (struct Node*)malloc(sizeof(struct Node));
node->data = val;
node->left = NULL;
node->right = NULL;
return node;
}
int main() {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("%d\n", maxDepth(root));
return 0;
}
Java
// Java program to find the maximum depth of a binary
// tree using depth-first search (DFS) approach.
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = null;
right = null;
}
}
// Returns "maxDepth" which is the number of nodes
// along the longest path from the root node down
// to the farthest leaf node.
class GfG {
static int maxDepth(Node node) {
if (node == null)
return 0;
// compute the depth of left and right subtrees
int lDepth = maxDepth(node.left);
int rDepth = maxDepth(node.right);
return Math.max(lDepth, rDepth) + 1;
}
public static void main(String[] args) {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
System.out.println(maxDepth(root));
}
}
Python
# Python program to find the maximum depth of a binary
# tree using depth-first search (DFS) approach.
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Returns "maxDepth" which is the number of nodes
# along the longest path from the root node down
# to the farthest leaf node.
def maxDepth(node):
if node is None:
return 0
# compute the depth of left and right subtrees
lDepth = maxDepth(node.left)
rDepth = maxDepth(node.right)
return max(lDepth, rDepth) + 1
if __name__ == "__main__":
# Representation of the input tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print(maxDepth(root))
C#
// C# program to find the maximum depth of a binary
// tree using depth-first search (DFS) approach.
using System;
class Node {
public int Data;
public Node left, right;
public Node(int val) {
Data = val;
left = null;
right = null;
}
}
// Returns "MaxDepth" which is the number of nodes
// along the longest path from the root node down
// to the farthest leaf node.
class GfG {
static int MaxDepth(Node node) {
if (node == null)
return 0;
// compute the depth of left and right subtrees
int lDepth = MaxDepth(node.left);
int rDepth = MaxDepth(node.right);
return Math.Max(lDepth, rDepth) + 1;
}
static void Main() {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
Console.WriteLine(MaxDepth(root));
}
}
JavaScript
// JavaScript program to find the maximum depth of
// a binary tree using depth-first search (DFS) approach.
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Returns "maxDepth" which is the number of nodes
// along the longest path from the root node down
// to the farthest leaf node.
function maxDepth(node) {
if (node === null)
return 0;
// compute the depth of left and right subtrees
const lDepth = maxDepth(node.left);
const rDepth = maxDepth(node.right);
return Math.max(lDepth, rDepth) + 1;
}
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
console.log(maxDepth(root));
Below is the illustration of above approach:
Example: Consider the following tree –

maxDepth(â12â) = max(maxDepth(â8âē), maxDepth(â18â)) + 1 = 2 + 1 = 3
because recursively
maxDepth(â8â) = max (maxDepth(â5âē), maxDepth(â11â)) + 1 = 1 + 1
maxDepth(â18â) = max (maxDepth(NULL), maxDepth(âNULL)) + 1 = 0 + 1 = 1
maxDepth(â5â) = max (maxDepth(NULL), maxDepth(âNULL)) + 1 = 0 + 1 = 1
maxDepth(â11â) = max (maxDepth(NULL), maxDepth(âNULL)) + 1 = 0 + 1 = 1
Time Complexity: O(n), where n is the number of nodes in the binary tree, as each node is visited once. (Please see the post on Tree Traversal for details)
Auxiliary Space: O(h) where h is height of the binary tree.
[Expected Approach – 2] Using Level Order Traversal – O(n) Time and O(n) Space
The idea is, if we take a closer look at the depth first traversal, we can notice that after we process the last node of the current level, the next level is completely in the queue. We use this property and insert a special NULL into the queue to indicate end of a level.
Follow the steps below to solve the problem:
- Traverse the tree in level order traversal starting from root.
- Initialize an empty queue q, a variable depth and push root, then push null into the q to indicate end of the first level.
- Run a while loop till q is not empty.
- Store the front element of q and Pop out the front element.
- If the front of q is NULL, it means we have processed the last node of current level and complete next level is in the queue. So we increment depth and insert a NULL for end of the next level.
- Else if the element is not NULL then check for its left and right children and if they are not NULL push them into q.
- Return depth.
Below is the Implementation of the above approach:
C++
// C++ program to find the height (depth) of a binary
// tree using level order traversal approach.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node *left, *right;
Node(int val) {
key = val;
left = nullptr;
right = nullptr;
}
};
// Function to find the height (depth) of the tree
int height(Node* root) {
if (!root) return 0;
// Initializing a variable to count
// the height of the tree
int depth = 0;
queue<Node*> q;
// Pushing the first level element
// along with nullptr
q.push(root);
q.push(nullptr);
while (!q.empty()) {
Node* curr = q.front();
q.pop();
// When nullptr is encountered,
// increment the depth
if (curr == nullptr) {
depth++;
// If queue still has elements left,
// push nullptr again to the queue
if (!q.empty()) {
q.push(nullptr);
}
}
else {
// If nullptr is not encountered,
// keep moving
if (curr->left) q.push(curr->left);
if (curr->right) q.push(curr->right);
}
}
return depth;
}
int main() {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
cout << height(root);
return 0;
}
Java
// Java program to find the height (depth) of a binary
// tree using level order traversal approach.
import java.util.LinkedList;
import java.util.Queue;
class Node {
int key;
Node left, right;
Node(int val) {
key = val;
left = null;
right = null;
}
}
// Function to find the height (depth) of the tree
class GfG {
static int height(Node root) {
if (root == null) return 0;
// Initializing a variable to count
// the height of the tree
int depth = 0;
Queue<Node> q = new LinkedList<>();
// Pushing the first level element
// along with null
q.add(root);
q.add(null);
while (!q.isEmpty()) {
Node curr = q.poll();
// When null is encountered,
// increment the depth
if (curr == null) {
depth++;
// If queue still has elements left,
// push null again to the queue
if (!q.isEmpty()) {
q.add(null);
}
}
else {
// If null is not encountered,
// keep moving
if (curr.left != null) q.add(curr.left);
if (curr.right != null) q.add(curr.right);
}
}
return depth;
}
public static void main(String[] args) {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
System.out.println(height(root));
}
}
Python
# Python program to find the height (depth) of a binary
# tree using level order traversal approach.
from collections import deque
class Node:
def __init__(self, val):
self.key = val
self.left = None
self.right = None
# Function to find the height (depth) of the tree
def height(root):
if not root:
return 0
# Initializing a variable to count
# the height of the tree
depth = 0
q = deque()
# Pushing the first level element
# along with None
q.append(root)
q.append(None)
while q:
curr = q.popleft()
# When None is encountered,
# increment the depth
if curr is None:
depth += 1
# If queue still has elements left,
# push None again to the queue
if q:
q.append(None)
else:
# If None is not encountered,
# keep moving
if curr.left:
q.append(curr.left)
if curr.right:
q.append(curr.right)
return depth
if __name__ == "__main__":
# Representation of the input tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print(height(root))
C#
// C# program to find the height (depth) of a binary
// tree using level order traversal approach.
using System;
using System.Collections.Generic;
class Node {
public int key;
public Node left, right;
public Node(int val) {
key = val;
left = null;
right = null;
}
}
// Function to find the height (depth) of the tree
class GfG {
static int Height(Node root) {
if (root == null) return 0;
// Initializing a variable to count
// the height of the tree
int depth = 0;
Queue<Node> q = new Queue<Node>();
// Pushing the first level element
// along with null
q.Enqueue(root);
q.Enqueue(null);
while (q.Count > 0) {
Node curr = q.Dequeue();
// When null is encountered,
// increment the depth
if (curr == null) {
depth++;
// If queue still has elements left,
// push null again to the queue
if (q.Count > 0) {
q.Enqueue(null);
}
}
else {
// If null is not encountered,
// keep moving
if (curr.left != null) q.Enqueue(curr.left);
if (curr.right != null) q.Enqueue(curr.right);
}
}
return depth;
}
static void Main() {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
Console.WriteLine(Height(root));
}
}
JavaScript
// JavaScript function to find the height (depth)
// of a binary tree using level order traversal approach.
class Node {
constructor(val) {
this.key = val;
this.left = null;
this.right = null;
}
}
// Function to find the height (depth) of the tree
function height(root) {
if (root === null) return 0;
// Initializing a variable to count
// the height of the tree
let depth = 0;
let q = [];
// Pushing the first level element
// along with null
q.push(root);
q.push(null);
while (q.length > 0) {
let curr = q.shift();
// When null is encountered,
// increment the depth
if (curr === null) {
depth++;
// If queue still has elements left,
// push null again to the queue
if (q.length > 0) {
q.push(null);
}
}
else {
// If null is not encountered,
// keep moving
if (curr.left) q.push(curr.left);
if (curr.right) q.push(curr.right);
}
}
return depth;
}
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
console.log(height(root));
Time Complexity: O(n), where n is the number of nodes, as each node is processed once.
Auxiliary Space: O(n), since in the worst case, all nodes of the last level (around n/2) could be in the queue simultaneously.
[Alternate Approach] Using Level Order Traversal – O(n) Time and O(n) Space
This method also uses the same concept that when we process the last node of a current level, the next level is completely in the queue. Instead of adding a null in the Queue. Simply increase the counter when the level increases and push the children of current node into the queue, then remove all the nodes from the queue of the current Level.
C++
// C++ program to find the height (depth) of a binary
// tree using level order traversal approach 2.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node *left, *right;
Node(int val) {
key = val;
left = nullptr;
right = nullptr;
}
};
// Function to find the height (depth)
// of the tree
int height(Node* root) {
if (!root) return 0;
// Initializing a queue to traverse
// the tree level by level
queue<Node*> q;
q.push(root);
int h = 0;
// Loop until the queue is empty
while (!q.empty()) {
int size = q.size();
// Traverse all nodes at the current level
for (int i = 0; i < size; i++) {
Node* temp = q.front();
q.pop();
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
}
// Increment height after traversing each level
h++;
}
return h;
}
int main() {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
cout << height(root);
return 0;
}
Java
// Java program to find the height (depth) of a binary
// tree using level order traversal approach 2.
import java.util.LinkedList;
import java.util.Queue;
class Node {
int key;
Node left, right;
Node(int val) {
key = val;
left = null;
right = null;
}
}
// Function to find the height (depth) of the tree
class GfG {
static int height(Node root) {
if (root == null) return 0;
// Initializing a queue to traverse
// the tree level by level
Queue<Node> q = new LinkedList<>();
q.add(root);
int h = 0;
// Loop until the queue is empty
while (!q.isEmpty()) {
int size = q.size();
// Traverse all nodes at the current level
for (int i = 0; i < size; i++) {
Node temp = q.poll();
if (temp.left != null) q.add(temp.left);
if (temp.right != null) q.add(temp.right);
}
// Increment height after traversing each level
h++;
}
return h;
}
public static void main(String[] args) {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
System.out.println(height(root));
}
}
Python
# Python program to find the height (depth) of a binary
# tree using level order traversal approach 2.
from collections import deque
class Node:
def __init__(self, val):
self.key = val
self.left = None
self.right = None
# Function to find the height (depth) of the tree
def height(root):
if root is None:
return 0
# Initializing a queue to traverse
# the tree level by level
q = deque([root])
h = 0
# Loop until the queue is empty
while q:
size = len(q)
# Traverse all nodes at the current level
for _ in range(size):
temp = q.popleft()
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
# Increment height after traversing each level
h += 1
return h
if __name__ == "__main__":
# Representation of the input tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print(height(root))
C#
// C# program to find the height (depth) of a binary
// tree using level order traversal approach 2.
using System;
using System.Collections.Generic;
class Node {
public int key;
public Node left, right;
public Node(int val) {
key = val;
left = null;
right = null;
}
}
// Function to find the height (depth) of the tree
class GfG {
static int Height(Node root) {
if (root == null) return 0;
// Initializing a queue to traverse
// the tree level by level
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
int h = 0;
// Loop until the queue is empty
while (q.Count > 0) {
int size = q.Count;
// Traverse all nodes at the current level
for (int i = 0; i < size; i++) {
Node temp = q.Dequeue();
if (temp.left != null) q.Enqueue(temp.left);
if (temp.right != null) q.Enqueue(temp.right);
}
// Increment height after traversing each level
h++;
}
return h;
}
static void Main() {
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
Console.WriteLine(Height(root));
}
}
JavaScript
// Javascript program to find the height (depth) of a binary
// tree using level order traversal approach 2.
class Node {
constructor(val) {
this.key = val;
this.left = null;
this.right = null;
}
}
// Function to find the height (depth) of the tree
function height(root) {
if (root === null) return 0;
// Initializing a queue to traverse
// the tree level by level
let q = [root];
let h = 0;
// Loop until the queue is empty
while (q.length > 0) {
let size = q.length;
// Traverse all nodes at the current level
for (let i = 0; i < size; i++) {
let temp = q.shift();
if (temp.left) q.push(temp.left);
if (temp.right) q.push(temp.right);
}
// Increment height after traversing each level
h++;
}
return h;
}
// Representation of the input tree:
// 1
// / \
// 2 3
// / \
// 4 5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
console.log(height(root));
Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(n)