The user wants a program to find the maximum depth of a binary tree.
I need to provide code for this.
I should choose a popular language; Python is usually the best choice for clarity, but I could also provide C++ or Java if requested. Since no language is specified, I'll stick to Python but maybe mention the logic is universal.
Understanding the problem:
- "Maximum depth" (or height) of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node.
- A tree with just a root node has depth 1 (or 0, depending on convention, but usually 1 for "number of nodes" or max depth defined as max(root.left, root.right) + 1 where base case is 0 for None).
- Base case: If the node is None (empty), the depth is 0.
- Recursive step: Depth of current node = 1 + max(depth of left child, depth of right child).
Approaches:
-
Recursive (Depth First Search - DFS): This is the most intuitive and standard way.
- Time Complexity: O(n) (visiting every node once).
- Space Complexity: O(h) where h is height (for recursion stack). Worst case O(n) for skewed tree.
-
Iterative (Breadth First Search - BFS / Level Order Traversal):
- Use a queue.
- Count the levels.
- Time Complexity: O(n).
- Space Complexity: O(w) where w is max width. Worst case O(n).
Structure of the response:
- Define the
TreeNode class (standard boilerplate).
- Provide the Recursive solution (most likely what's expected).
- Provide the Iterative solution (good alternative).
- Add a main block to test it.
Drafting the Code (Python):
Class:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
Recursive Solution:
def maxDepth(root):
if not root:
return 0
left_depth = maxDepth(root.left)
right_depth = maxDepth(root.right)
return max(left_depth, right_depth) + 1
Iterative Solution (BFS):
from collections import deque
def maxDepthIterative(root):
if not root:
return 0
queue = deque([root])
depth = 0
while queue:
depth += 1
level_size = len(queue)
for _ in range(level_size):
node = queue.popleft()
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return depth
Refining the output:
- Start with the recursive approach as it's the standard definition.
- Explain the logic.
- Provide a usage example.
- Keep it clean.
Let's write the final response. I will provide the Python solution.
Here is a solution in Python. It uses a recursive approach (Depth First Search), which is the most intuitive way to solve this problem.
The Logic
The maximum depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node.
- Base Case: If the tree is empty (node is
None), the depth is 0.
- Recursive Step: If the tree is not empty, the depth is
1 plus the maximum of the depth of the left subtree and the right subtree.
Code
# 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
def max_depth(root):
"""
Finds the maximum depth of a binary tree using recursion.
"""
# Base case: If the tree is empty, return 0
if root is None:
return 0
# Recursive step:
# Calculate depth of left and right subtrees
left_depth = max_depth(root.left)
right_depth = max_depth(root.right)
# Total depth is 1 (current node) + the larger of the two children
return max(left_depth, right_depth) + 1
# --- Example Usage ---
if __name__ == "__main__":
# Constructing the following tree:
# 3
# / \
# 9 20
# / \
# 15 7
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print(f"The maximum depth of the tree is: {max_depth(root)}")
Alternative: Iterative Approach (Breadth-First Search)
If the tree is extremely deep, recursion might cause a stack overflow error. In that case, you can use an iterative approach using a Queue (Level Order Traversal):
from collections import deque
def max_depth_iterative(root):
if not root:
return 0
queue = deque([root])
depth = 0
while queue:
depth += 1
# Process all nodes at the current level
level_size = len(queue)
for _ in range(level_size):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth