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 interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. Me at 2amCharacter joke · No posting date

    My code works. I have no idea why. I am afraid to touch it. I am going to bed.

  2. Rubber DuckCharacter joke · No posting date

    Quack. (Translation: have you tried printing it?)

  3. RecruiterCharacter joke · No posting date

    We loved your energy. We went with the candidate whose code compiled.