104. Maximum Depth of Binary Tree
Problem:
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.
Solution:
This problem uses a Depth-First Search (DFS) approach to calculate the maximum depth of a binary tree. The idea is to recursively determine the depth of the left and right subtrees and then return the greater of the two depths, incremented by one to account for the current node. The base case occurs when the function encounters a null node (indicating an empty subtree), in which case it returns a depth of zero.
This approach ensures that all nodes in the binary tree are visited once, making it efficient. The time complexity of this solution is O(N)
, where N
is the number of nodes in the tree. The space complexity is O(H)
, where H
is the height of the tree, as the recursion stack can grow up to the depth of the tree. This problem highlights the use of recursion for solving tree traversal problems and provides an excellent foundation for understanding divide-and-conquer strategies in tree-based algorithms.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return 1 + max(left,right)