104. Maximum Depth of Binary Tree ๐
Last updated
Last updated
Difficulty: Easy
- Tags: Binary Tree
, DFS
, BFS
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.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
The number of nodes in the tree is in the range [0, 10โด]
.
-100 <= Node.val <= 100
.
To determine the maximum depth of the binary tree, we can use two common approaches:
Depth-First Search (DFS): Traverse the tree recursively and calculate the depth at each level.
Breadth-First Search (BFS): Use a queue to traverse level by level, tracking the depth.
Recursive DFS:
At each node, compute the depth of the left and right subtrees recursively.
The maximum depth at any node is 1 + max(leftDepth, rightDepth)
.
Iterative BFS:
Use a queue to traverse the tree level by level.
Each level's nodes are processed, and their children are added to the queue.
Increment the depth counter after processing each level.
DFS: O(n), where n
is the number of nodes in the tree.
BFS: O(n), since each node is visited exactly once.
DFS: O(h), where h
is the height of the tree (stack space for recursion).
BFS: O(n), for the queue to store nodes at each level.
Compare the performance of recursive DFS versus iterative BFS for very large trees.
Consider using a stack-based iterative DFS implementation for avoiding stack overflow in deep trees.
You can find the full solution: to-learn here, to coding interview here.