Maximum Depth of Binary Tree — Day 37(Python)

Image for post
Image for post
Photo by jose Fernandez conde on Unsplash

Today’s question is based on Trees. It tests your understanding of trees and recursion. It is an “Easy” tagged question in Leetcode. Let us look into the question.

104. Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:

Example 2:

Example 3:

Example 4:

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -100 <= Node.val <= 100

The question requires us to find the maximum depth of the tree, which means we have to find the height of the tree. To find the height of the tree we would have to start from the root node and go until the leaf node. There can be multiple leaf nodes, we need to find the maximum among the recorded heights. We will be using recursion to solve this problem.

Before we use recursion, we need to understand what needs to be our base condition.

When the root is None, we should return 0.

Okay, now let's look at the code snippet.

Complexity analysis.

Time Complexity

We are visiting each node once and hence the time complexity is O(N) where N is the number of nodes in the Tree.

Space Complexity.

We are visiting each node recursively, hence the space complexity is O(N).

I would love to hear your feedback about my posts. Do let me know if you have any comments or feedback.

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store