104. Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth.
Approach: DFS
Use depth-first search to traverse the tree and calculate the maximum depth.
Algorithm:
- If the root is None, return 0.
- Recursively calculate the maximum depth of the left and right subtrees.
- Return the maximum of the two depths plus 1.
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1- Time: — where is the number of nodes in the tree, as we visit each node exactly once.
- Space: — where is the height of the tree, due to the recursive call stack.
Last updated on