Python coding

Closest shared ancestor

Write shared_ancestor(root, p, q): given the root of a binary tree and two different nodes p and q that are both in it, return the deepest node whose subtree contains both of them. A node belongs to its own subtree, so if p sits above q, the answer is p. It is not a search tree: the values are distinct but in no particular order. Each TreeNode has val, left and right.

The tests call the provided run_shared_ancestor(values, p, q), where values lists the tree level by level with null for a missing child ([1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3), p and q are the values of the two nodes, and the result is the value of the node you return.

Aim for one pass over the tree.

Besides the tests, one large input (a 10,387-node tree, 653 levels tall) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • run_shared_ancestor([3,5,1,6,2,0,8,null,null,7,4], 6, 4) → 5
  • run_shared_ancestor([3,5,1,6,2,0,8,null,null,7,4], 5, 4) → 5
  • run_shared_ancestor([3,5,1,6,2,0,8,null,null,7,4], 7, 8) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Asking "is p in this subtree?" again at every level searches the same nodes over and over: O(n·h), quadratic on a tall tree. One postorder pass answers it for every node at once.

Hint 2

In postorder, let each call report what its subtree holds. Returning p, q or nothing from the bottom is enough information for the nodes above.

Hint 3

A node that is p or q returns itself without looking further. A node that gets something back from both sides is the answer; otherwise it passes up whichever side found something.

Solution and why it works
pythonO(n) · O(h), h = height (recursion stack)
# --- your code ---
def shared_ancestor(root: "TreeNode | None", p: "TreeNode", q: "TreeNode") -> "TreeNode | None":
    if root is None or root is p or root is q:
        return root                       # nothing here, or a target: report it upward
    left = shared_ancestor(root.left, p, q)
    right = shared_ancestor(root.right, p, q)
    if left and right:
        return root                       # p and q came up from different sides: the split
    return left or right                  # pass up whatever one side found


# --- provided: do not edit ---
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build_tree(values: list[int | None]) -> TreeNode | None:
    # Level order: each existing node takes the next two entries as its left and right child.
    nodes = [None if v is None else TreeNode(v) for v in values]
    children = iter(nodes[1:])
    for node in nodes:
        if node is not None:
            node.left = next(children, None)
            node.right = next(children, None)
    return nodes[0] if nodes else None


def find(root: TreeNode | None, val: int) -> TreeNode:
    stack = [root]
    while stack:
        node = stack.pop()
        if node is not None:
            if node.val == val:
                return node
            stack += [node.left, node.right]
    raise ValueError(f"{val} is not in the tree")


def run_shared_ancestor(values: list[int | None], p: int, q: int) -> int | None:
    root = build_tree(values)
    node = shared_ancestor(root, find(root, p), find(root, q))
    return None if node is None else node.val

Each call returns p or q if it found one below (or is one), else None. The first node that hears back from both sides is where the paths to p and q split: the answer, which then travels up unchanged. If p is above q, the search stops at p and nothing else comes back, so p wins, as it should. One visit per node: O(n). The trap is calling a separate "does this subtree contain p?" search at every level, which rescans the same nodes, O(n·h).