codejump
MediumPythonJavaScriptTypeScript

Binary Tree — Lowest Common Ancestor

Data StructuresTreesRecursionDFS

solve(levelOrder, p, q) — in a binary tree (not necessarily a search tree)
with unique values, return the value of the lowest common ancestor of the
nodes holding p and q: the deepest node that has both of them in its
subtree. A node counts as a descendant of itself.

Both p and q are guaranteed to exist in the tree.

Examples (tree [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4])

solve(tree, 5, 1)  → 3
solve(tree, 5, 4)  → 5   // a node is its own descendant
solve(tree, 6, 4)  → 5
solve(tree, 7, 8)  → 3

Without the BST ordering you cannot choose a side by comparing values — you have
to search both subtrees.

Sample tests

Test #1Nodes in different subtrees of the root
Input: [[3,5,1,6,2,0,8,null,null,7,4],5,1]
Output: 3
Test #2One node is the ancestor of the other
Input: [[3,5,1,6,2,0,8,null,null,7,4],5,4]
Output: 5
Test #3Root and its child
Input: [[1,2],1,2]
Output: 1