Lowest common ancestor · Compiler

Lowest common ancestor

Find the deepest node on both paths from the root to the two target nodes. Each node counts as its own ancestor. Use node IDs to distinguish nodes that store the same value.

Input
Read n (1 <= n <= 100), then n rows of value left right. Rows give nodes in ID order from 1 to n. Each value is an integer in [-1000, 1000]. Each child link is a node ID or 0 for a missing child. For n > 0, the links form one binary tree rooted at ID 1. After the node rows read two target IDs a b in [1, n]. The IDs may be equal.
Output
Print the stored value of the lowest common ancestor.

Compiler Explorer runs your code when you run or check it.

Loading your exercise draft…