Maximum Depth of Binary Tree — Day 37(Python)

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:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Example 3:

Input: root = []
Output: 0

Example 4:

Input: root = [0]
Output: 1


  • 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.

class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root == None:
return 0

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 @

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Welcome to gRPC, Please Follow Me…

Moving the Rari Capital Community to Discord!

Interview with an Android Engineer — Meet Nicolas Ioannou

How to read ram data in Linux?

Apply a business plan for your micro-service in Kubernetes

The first programming language you should learn… A debate…

Pandora — HTB(Hack The Box) Write-up

Build a GraphQL Server With Spring Boot and MySQL

Autumn in all around the world. But never-mind, it’s Springtime here. Enjoy the beauty. Credit goes to John Peel

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
Annamariya Tharayil

Annamariya Tharayil

Software Engineer. Find me @

More from Medium

Bellman-Ford Algorithm

Mutable and Immutability in Python

Chapter 01 — Overview of Java

Huffman coding | Greedy Algorithm