PythonStudio
Interview Problems

Diameter of a Binary Tree

easy · tree traversal

nodes maps unique string IDs to [left_id_or_None,right_id_or_None] for a valid binary tree rooted at root, or an empty tree when root is None. Return the largest number of EDGES on any path between two nodes; the path need not pass through root. Empty and one-node trees have diameter 0. There are at most 100 reachable nodes. Examples (JSON; null means Python None): Input: {"nodes": {"a": ["b", "c"], "b": ["d", "e"], "c": [null, null], "d": [null, null], "e": [null, null]}, "root": "a"} Output: 3 Input: {"nodes": {}, "root": null} Output: 0

Starter code

def tree_diameter(nodes: dict, root: str | None) -> int:
    """Compute the longest edge path from subtree heights."""
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python compiler