Maximum Depth of Binary Tree — Day 37(Python)
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
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.
Input: root = [3,9,20,null,null,15,7]
Input: root = [1,null,2]
Input: root = 
Input: root = 
- The number of nodes in the tree is in the range
-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.
def maxDepth(self, root: TreeNode) -> int:
if root == None:
We are visiting each node once and hence the time complexity is O(N) where N is the number of nodes in the Tree.
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.