VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-maximum-depth-or-height-of-a-tree/

⇱ Maximum Depth or Height of a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Depth or Height of a Binary Tree

Last Updated : 5 May, 2026

Given the root of a binary tree, 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:

👁 ex-11

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

Input:

👁 ex-4

Output: 3
Explanation: The longest path from the root (node 1) to deepest leaf (node 6) has 3 edges.

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 by 1 + max(leftHeight, rightHeight). The recursion bottoms out when we reach to a null node, which contributes a height of 0.

Consider the following tree for example to understand the flow.

👁 heightTree3

maxDepth('12') = max(maxDepth('8'), maxDepth('18')) + 1 = 1 + 1 = 2
because recursively 
maxDepth('8') =  max (maxDepth('5'), maxDepth('11')) + 1 = 0 + 1
maxDepth('18') = max (maxDepth(NULL), maxDepth('NULL)) + 1 = -1 + 1 = 0
maxDepth("5") = max (maxDepth(NULL), maxDepth('NULL)) + 1 = -1 + 1 = 0
maxDepth("11") = max (maxDepth(NULL), maxDepth('NULL)) + 1 = -1 + 1 = 0


Output
2

Time Complexity: O(n)
Auxiliary Space: O(h) where h is height of the binary tree. The height can be at most equal to number of nodes in case of skewed tree and O(Log n) in case of a balanced tree

Level Order Traversal

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.


Output
2

Time Complexity: O(n)
Auxiliary Space: O(n) where n is number of nodes. A more precise value of of space would be O(w) where w is width of the binary tree.


Comment