Maximum Depth of Binary Tree

Try to solve the Maximum Depth of Binary Tree problem.

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 #

Created with Fabric.js 3.6.6 3 9 10 5 6 Output Sample example 1 n 3 9 10 NULL NULL 5 6 3 Input

1 of 3

Created with Fabric.js 3.6.6 Output Input n 3 NULL 9 Sample example 2 3 9 2

2 of 3

Created with Fabric.js 3.6.6 Output Input Sample example 3 n 6 1 6

3 of 3

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

Question 1 of 30 attempted

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.

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

Initialize a counter to track the maximum depth seen so far and a stack for the depth of the current branch.

If the current node is NULL, return the counter.

Otherwise, check the depth of the left subtree and the depth of the right subtree.

If the depth of the current branch exceeds the maximum depth seen so far, update the maximum depth.

When all branches have been explored, return the maximum depth seen so far.


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
Input #1
%0 node_1 9 node_2 7 node_1->node_2 node_3 20 node_1->node_3 node_4 3 node_2->node_4 node_5 15 node_2->node_5
Visualization for Input #1
Maximum Depth of Binary Tree

Solution: Invert Binary Tree

Solution: Maximum Depth of Binary Tree