Maximum Depth of Binary Tree
Given the root of a binary tree, find its maximum depth.
The maximum depth is defined as the number of nodes along the longest path from the root node down to the farthest leaf node.
Function Signature:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root: TreeNode) -> int:
"""
Calculate the maximum depth of a binary tree.
Parameters:
- root: The root of the binary tree.
Returns:
- int: The maximum depth of the binary tree.
"""
# Your code here
Example:
# Example Binary Tree:
# 4
# / \
# 8 10
# / \
# 12 7
root = TreeNode(4,
TreeNode(8),
TreeNode(10,
TreeNode(12),
TreeNode(7)))
result = max_depth(root) # Maximum depth of the tree: 3
assert result == 3
print(result)
Note:
- The given binary tree is not necessarily a binary search tree.
- All node values are unique.
Instructions:
- Write the
max_depth
function to solve the problem. - Implement your solution in Python.
- Provide clear comments in your code.
- Discuss the time and space complexity of your solution.
As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊