KatInterview

Common Ancestor of Two Values, Only If Both Exist

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsbinary-treelowest-common-ancestorparent-map

Last updated

Find the lowest common ancestor of two values in a level-order encoded binary tree, returning null when either value is missing from the tree.

Shared Ancestor with Existence Check

You are given a binary tree in level-order list form, plus two integer values p and q. Find the lowest common ancestor (LCA) of the nodes holding p and q, but only if both values actually appear in the tree. If either one is missing, return None.

Tree encoding

The list tree lists node values level by level, from left to right, with None marking a missing child.

  • tree[0] is the root. If the list is empty or tree[0] is None, the tree is empty.
  • Nodes are processed in the order they appear. Each existing node consumes the next two list entries as its left child and right child. Missing children (None) have no children of their own and consume no further entries.
  • If the list ends early, all remaining children are absent.

For example, [3,5,1,6,2,0,8,None,None,7,4] has root 3 with children 5 and 1. Node 5 has children 6 and 2. Node 1 has children 0 and 8. Node 6 has no children, and node 2 has children 7 and 4.

Definition of the answer

  • The LCA of two nodes is the deepest node that has both of them in its subtree.
  • A node counts as being in its own subtree, so one of the targets can itself be the LCA.
  • All node values are unique, so a value identifies exactly one node.
  • If p == q and that value is in the tree, the answer is that value itself.
  • If p or q (or both) does not occur in the tree, or the tree is empty, return None.

Return the value of the LCA, not a node object.

Constraints

  • The tree has at most 100,000 nodes.
  • Node values and the targets p, q are signed 32-bit integers.
  • Node values are unique.
  • The tree may be empty or heavily skewed (for example, a chain of 100,000 nodes), so avoid relying on deep recursion.

Examples

Example 1

Input: common_ancestor_if_both_exist([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 4)

Output: 5

Example 2

Input: common_ancestor_if_both_exist([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 42)

Output: None

Hints

Hint 1

Returning as soon as you meet p or q is wrong when the other value may not exist. You need proof that both values are present.

Hint 2

Try recording each node's parent while you decode the level-order list. Then presence is a simple membership check, and the ancestor question becomes a walk upward.

Hint 3

Collect all ancestors of p (including p itself) in a set, then walk up from q until you hit a node in that set. Handle the empty tree and p == q before that.