Common Ancestor of Two Values, Only If Both Exist
Trees & GraphsAuto-graded · 18 test casesLast 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 ortree[0]isNone, 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 == qand that value is in the tree, the answer is that value itself. - If
porq(or both) does not occur in the tree, or the tree is empty, returnNone.
Return the value of the LCA, not a node object.
Constraints
- The tree has at most
100,000nodes. - Node values and the targets
p,qare 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The main risk is the shortcut of returning a node as soon as it equals p or q. That gives a wrong answer when the other target is missing, for example p = 5, q = 42. So we first establish that both values exist, and only then compute the ancestor.
- Decode the tree and record parents. Walk the level-order list with a queue. Each queued node takes the next two entries as its children. Every non-null child is added to the queue and stored in a
parentdictionary (value to parent value). The root's parent isNone. This iterates, so a 100,000-deep chain causes no recursion problems. - Check presence. If the tree is empty, or
porqis not a key inparent, returnNone. - Equal targets. If
p == qand it exists, the answer is that value. - Intersect ancestor chains. Walk from
pup to the root, storing every visited value (includingp) in a set. Then walk up fromquntil the current value is in the set. That first hit is the lowest common ancestor.
Why it is correct
- Every node's chain of parents leads to the root, so the two chains must meet, at the latest at the root.
- The first node on
q's upward path that also lies onp's upward path is the deepest node that is an ancestor (or self) of both, which is the definition of the LCA. - Starting each chain at the node itself handles the case where one target is an ancestor of the other. For instance, if
pis aboveq, thenpis already in the set whenq's walk reaches it. - Absent values never appear in
parent, so the presence check returnsNoneexactly when the problem requires it. - Unique values let us use the values directly as dictionary keys.
Complexity
- Time: O(n). Decoding visits each entry once, and the two upward walks are each at most the tree height, which is at most n.
- Space: O(n) for the parent map, the queue, and the ancestor set.
Reference solution
from typing import List, Optional
def common_ancestor_if_both_exist(tree: List[Optional[int]], p: int, q: int) -> Optional[int]:
if not tree or tree[0] is None:
return None
# Decode the level-order list, recording each value's parent.
parent = {tree[0]: None}
queue = [tree[0]]
head = 0
index = 1
n = len(tree)
while head < len(queue) and index < n:
node = queue[head]
head += 1
for _ in range(2):
if index >= n:
break
child = tree[index]
index += 1
if child is not None:
parent[child] = node
queue.append(child)
# Both targets must exist.
if p not in parent or q not in parent:
return None
if p == q:
return p
# All ancestors of p, including p itself.
ancestors = set()
node = p
while node is not None:
ancestors.add(node)
node = parent[node]
# Climb from q until we reach an ancestor of p.
node = q
while node not in ancestors:
node = parent[node]
return node