The user wants a program to find the maximum depth of a binary tree.
1. Understand the Goal:
The goal is to calculate the "height" of a binary tree. The maximum depth is defined as the number of nodes along the longest path from the root node down to the farthest leaf node.
2. Choose a Programming Language:
Python is generally the most accessible and widely used language for algorithmic problems like this due to its readability. I should also provide a C++ or Java version if the user didn't specify, or just stick to Python but explain the logic well so it can be translated. I will provide Python as the primary example, and maybe C++ for a statically typed perspective, but Python is usually sufficient for a general request. Let's stick to Python for clarity, maybe offer C++ as an alternative or just keep it simple with Python. I'll provide Python code.
3. Define the Tree Node Structure:
A standard binary tree node usually has:
A value (val)
A left child (left)
A right child (right)
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
4. Determine the Approach:
There are two main ways to solve this:
Recursive (Depth-First Search - DFS): This is the most intuitive.
Return max(left_depth, right_depth) + 1 (for the current node).
Code:
python
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
6. Develop the Iterative Solution (BFS):Logic:
If root is null, return 0.
Queue = [root], depth = 0.
While queue is not empty:
Increment depth.
For each element currently in the queue (current level):
Pop node.
Push children (if they exist).
Return depth.
Code:
python
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
7. Structure the Output:
Define the TreeNode class.
Provide the Recursive approach (easiest to understand).
Provide the Iterative approach (good for avoiding recursion limit issues).
Provide example usage to show how to build a tree and run the function.
8. Refine the Code and Explanations:
Make sure variable names are clear.
Add comments explaining why it works.
The recursive solution is preferred for interviews unless space complexity is a major concern (recursion stack vs queue), but the iterative BFS is good to show breadth of knowledge. I will present the recursive one first as it's the standard answer.
Let's stick to Python for the main answer as it's pseudo-code friendly, but I'll write it so it's valid running code.
Self-Correction/Edge Cases:
Empty tree: root is None. The code handles this (if not root: return 0).
Single node: root exists, children are None. max(0, 0) + 1 = 1. Correct.
Skewed tree (linked list): Will recurse N times. Could hit recursion limit in Python. The iterative solution is safer for extremely deep trees, but the recursive one is standard for the algorithm. I will provide the recursive one as the primary answer but mention the iterative one.
Actually, I should probably provide both Recursive (DFS) and Iterative (BFS) to be thorough.
Plan:
Define TreeNode.
Implement Recursive solution.
Implement Iterative solution.
Provide a complete runnable example.
Let's write the response.
Here is a solution in Python. I have included two approaches: the Recursive approach (which is the most common and concise) and the Iterative approach (which uses a queue).
1. Define the Tree Node
First, we need a class to represent the nodes in the binary tree.
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
2. Approach 1: Recursion (Depth First Search)
This is the standard way to solve this problem. The logic is simple:
If the node is None, the depth is 0.
Otherwise, the depth is 1 plus the maximum depth of its children.
python
def max_depth_recursive(root):
# Base case: If tree is empty, depth is 0
if root is None:
return 0
# Recursive step: 1 (current node) + max depth of left or right child
left_depth = max_depth_recursive(root.left)
right_depth = max_depth_recursive(root.right)
return 1 + max(left_depth, right_depth)
3. Approach 2: Iteration (Breadth First Search)
If the tree is extremely deep, recursion might cause a stack overflow. An iterative approach using a Queue (Level Order Traversal) is safer. We count how many levels (layers) of nodes we visit.
python
from collections import deque
def max_depth_iterative(root):
if root is None:
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
4. Complete Example
Here is a runnable script combining everything:
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root):
if root is None:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
# --- Setup a test tree ---
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# Calculate depth
print("Maximum Depth:", max_depth(root)) # Output: 3