The lowest common ancestor (LCA) of two nodes is the deepest node that has both of them as descendants (a node is a descendant of itself). The tree is a general binary tree with no ordering guarantee, so you must search it. Given two distinct values a and b that both appear in the tree, output the value of their LCA.
One line: the binary tree as a level-order array.
The tree is encoded on ONE line as a space-separated level-order (breadth-first) array. The token null marks a missing child; the children of a null are omitted from the array. An empty tree is written as the single token null.
The next line: two space-separated integers a and b, the values of the two query nodes.
A single integer: the value stored at the lowest common ancestor of the two query nodes.
Example 1
Input
1 2 3 4 5 null 6 4 5
Expected
2
Explanation
Nodes 4 and 5 are both children of node 2, so their lowest common ancestor is 2.
Example 2
Input
1 2 3 4 5 null 6 4 6
Expected
1
Explanation
Node 4 is under 2 and node 6 is under 3, so the deepest node containing both is the root, 1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →