[
tree
recursion
dfs
]
Leetcode 0104. Maximum Depth of Binary Tree
https://leetcode.com/problems/maximum-depth-of-binary-tree
This is classical problem about tree traversal and there are as usual 2 different approach how you can do it (bfs and dfs) and we can choose whatever you want. Recursive dfs will provide us with the shortest code, so I chose this one.
- If we reached
None
node, it means we need to return depth equal to0
. - In other case, we check depths of left and right subtrees and return maximum of them plus one.
Complexity: As for usual dfs approach, time complexity is O(n)
and space complexity is O(h)
, where h
is height of our tree.
class Solution:
def maxDepth(self, root):
if not root: return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
If you like the solution, you can upvote it on leetcode discussion section: Problem 0104