Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Depth-First Search (DFS)
root
is None
. If it is, return 0
since the tree is empty.dfs
to traverse the tree recursively.1
plus the maximum depth of its left and right subtrees.None
, return the depth - 1
(to account for the extra increment before the leaf node).# 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
return self.dfs(root, 1)
def dfs(self, node: Optional[TreeNode], depth: int) -> int:
if not node:
return depth - 1
left_depth = self.dfs(node.left, depth + 1)
right_depth = self.dfs(node.right, depth + 1)
return max(left_depth, right_depth)