FresherFresher (0–1 yrs)CodingPythonAmazonMicrosoft
Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth (number of nodes along the longest root-to-leaf path).
Answers use simple, clear English.
Time: O(n)Space: O(h)
Quick interview answer
DFS recursively: depth = 1 + max(left, right); null is 0. BFS level-order also works by counting levels.
Detailed answer
DFS recursively: depth = 1 + max(left, right); null is 0. BFS level-order also works by counting levels. Clarify depth vs height terminology if the interviewer uses different words.
Full explanation
Clarify depth vs height terminology if the interviewer uses different words.
Real example & use case
Org-chart depth check to limit nested manager chains in HR software.
Pros & cons
Pros: recursive DFS is tiny. Cons: recursion depth risk on skewed trees — iterative stack/BFS safer.
Code example
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def max_depth(root: TreeNode | None) -> int:
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))Practice code · python (view only · no execution)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def max_depth(root: TreeNode | None) -> int:
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))#tree#dfs