Problem 434190 · medium · Level 04 Non-Linear Data Structures

Lowest Common Ancestor

binary tree · recursion · DFS

In a family tree, the most recent forebear two people share is their lowest common ancestor (LCA): of all the nodes with both people somewhere beneath them, it is the deepest one. Here a node counts as being beneath itself, so when one of the two is an ancestor of the other, that ancestor is the LCA.

Write lowest_common_ancestor(root, p, q). The node values are all distinct, p and q are two values that both occur in the tree, and you return the value of their LCA.

Examples

          10
        /    \
       7      4
      /      / \
     1      8   0
    / \          \
   6   2          11

Input:  root = [10, 7, 4, 1, None, 8, 0, 6, 2, None, None, None, 11], p = 7, q = 4
Output: 10
Input:  root = [10, 7, 4, 1, None, 8, 0, 6, 2, None, None, None, 11], p = 7, q = 2
Output: 7
Explanation: 7 is an ancestor of 2, so it is its own LCA with 2.
5
 \
  3

Input:  root = [5, None, 3], p = 3, q = 5
Output: 5

Constraints

  • 2 <= number of nodes <= 1000
  • All values are distinct, and p != q both exist in the tree.

Goals

  • Return information upwards from recursive calls and combine it at each node
  • Reason about the three cases: both targets on the left, both on the right, or split
  • Distinguish 'not found' (None) from a found value of 0
Starting Python…