easy +10 pts

Maximum depth of tree

Compute the height of a binary tree node by node.

Given the root of a binary tree, write a function `max_depth(root)` that returns the maximum depth (height) of the tree. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. A binary tree node is represented as a dictionary with keys `val`, `left`, and `right`. For example, a node with value 3, left child 9, and right child 20 would be `{'val': 3, 'left': {'val': 9, 'left': None, 'right': None}, 'right': {'val': 20, 'left': None, 'right': None}}`. The `left` and `right` values are either `None` (no child) or another dictionary with the same structure. If the tree is empty (`root is None`), the depth is `0`. The root node itself counts as depth `1`. Your task: implement `max_depth(root)` that takes such a dictionary-based root (or `None`) and returns the maximum depth as an integer.

Constraints

- The number of nodes in the tree is in the range [0, 10^4]. - Node values are integers. - The function should run in O(n) time and O(n) recursion stack space (or O(n) iterative space). - The input tree is a valid binary tree where each node is either `None` or a dictionary with keys `val`, `left`, `right`.

Example

>>> # Example 1: tree = [3,9,20,None,None,15,7]
>>> root = {'val': 3, 'left': {'val': 9, 'left': None, 'right': None}, 'right': {'val': 20, 'left': {'val': 15, 'left': None, 'right': None}, 'right': {'val': 7, 'left': None, 'right': None}}}
>>> max_depth(root)
3

>>> # Example 2: empty tree
>>> max_depth(None)
0

>>> # Example 3: single node
>>> max_depth({'val': 1, 'left': None, 'right': None})
1
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think recursively: the depth of a node is 1 plus the maximum depth of its children.
The base case is when root is None: return 0.
Since nodes are dictionaries, access children with root['left'] and root['right'].
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.