Search⌘ K
AI Features

Maximum Depth of Binary Tree

Explore how to find the maximum depth of a binary tree by analyzing the longest path from root to leaf. Learn to apply depth-first search techniques and optimize your solution for time and space complexity.

Statement

You are given the root of a binary tree, and your task is to determine the maximum depth of this tree. The maximum depth of a binary tree is determined by the count of nodes found on the longest path from the root node to the farthest leaf node.

Constraints:

  • The number of nodes in the tree is in the range [1,500].[1, 500].

  • 100-100 \leqNode.data 100\leq 100

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Maximum Depth of Binary Tree

1.

What is the maximum depth of the following tree?

root = [1, 2, 3, 4, 5]

     1
    / \
   2   3
  / \ 
 4   5 
A.

7

B.

3

C.

2

D.

4


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O(n) time and takes O(n) space. You may try to translate the logic of the solved puzzle into a coded solution.

Python
usercode > main.py
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, data):
# self.data = data
# self.left = None
# self.right = None
from ds_v1.BinaryTree.BinaryTree import TreeNode
from collections import deque
def find_max_depth(root):
# Replace this placeholder return statement with your code
return -1
Maximum Depth of Binary Tree