Binary Tree Lowest Common Ancestor
Medium · Coding & Algorithms · Machine Learning Engineer · Onsite
Problem Statement
Given the root of an arbitrary binary tree root along with two distinct integer values p and q guaranteed to appear in the tree, return the integer value of their lowest common ancestor (LCA).
All node values in the tree are unique integers, and the tree does not follow binary-search-tree ordering. In standard level-order list inputs, entries appear top-to-bottom and left-to-right with None (null) marking absent child pointers (and omitted descendants below None).
Here, node u is an ancestor of node v whenever u lies along the path from the root down to v—including the case u == v, where u itself is one of the two queried targets. Among all common ancestors of p and q, return the value stored at the deepest one.
Examples
Example 1
- Input:
root = [10, 4, 7, 12, 2, None, 9, None, None, 15, 6], p = 15, q = 9 - Output:
10 - Explanation: Node
15sits along the left branch10 -> 4 -> 2 -> 15while node9sits along the right branch10 -> 7 -> 9, so10is the deepest node above both.
Example 2
- Input:
root = [10, 4, 7, 12, 2, None, 9, None, None, 15, 6], p = 4, q = 6 - Output:
4 - Explanation: Node
6lies below node4(4 -> 2 -> 6), and every node counts as its own ancestor, making4the deepest shared ancestor.
Example 3
- Input:
root = [8, -2], p = -2, q = 8 - Output:
8 - Explanation: In this two-node tree,
-2is the left child of root8, so8is an ancestor of both-2and8.
Constraints
- The binary tree has between
2and100000nodes inclusive. -1000000000 <= node.val <= 1000000000, and every node has a distinct value.p != q, and bothpandqexist in the tree.
Step-by-step walkthrough
Understand the problem and the input format
In a binary tree, node
ais an ancestor of nodebwheneveralies along the path from the root down tob— includinga == b, since every node is treated as an ancestor of itself. Given two distinct target integerspandq(every node in the tree stores a unique integer), their lowest common ancestor (LCA) is the deepest node that is an ancestor of bothpandq.Look closely at how
lowestCommonAncestorValue(root, p, q)is invoked in the examples:rootcan be passed as a level-order serialized list such as[10, 4, 7, 12, 2, None, 9, None, None, 15, 6], and the return value is anint(rather than a node object).Level-order list: [10, 4, 7, 12, 2, None, 9, None, None, 15, 6] 10 <-- LCA(15, 9) = 10 / \ 4 7 <-- LCA(4, 6) = 4 (4 lies above 6 and counts as its own ancestor) / \ \ 12 2 9 / \ 15 6 <-- LCA(15, 6) = 2Keep in mind that this is an arbitrary binary tree rather than a binary search tree — values are unordered (
12sits to the left of4!), so comparingpandqnumerically againstnode.valcannot tell us which branch holds them.Build the `TreeNode` adapter from a level-order list
In standard level-order list format,
raw_root[0]is the root, followed by the left and right children of each non-null node from top to bottom, left to right (Noneentries have no children listed after them).We reconstruct
TreeNodeobjects using a first-in-first-out (FIFO) queue (collections.deque, which pops from the front inO(1)time):- Create
root = TreeNode(raw_root[0])and push it intoqueue, startingidx = 1. - Pop
parentfrom the front ofqueue. Readraw_root[idx]forparent.left(checkingis not Noneexplicitly because0is a valid node value!), advanceidx, and do the same forparent.right. - Check
isinstance(raw_root, (list, tuple))first so if a caller passes a pre-built node object directly, we return it unchanged.
from collections import deque from typing import Any, Optional class TreeNode: """Binary tree node constructed from the serialized level-order input list.""" def __init__( self, val: int, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None, ) -> None: self.val = val self.left = left self.right = right def _build_tree(raw_root: Any) -> Optional[TreeNode]: """Convert a level-order list like [10, 4, 7, None, 9] (or an existing node) into a TreeNode root.""" if raw_root is None: return None # Support callers that pass an already-constructed node object directly. if not isinstance(raw_root, (list, tuple)): return raw_root if not raw_root or raw_root[0] is None: return None root = TreeNode(raw_root[0]) # queue: FIFO queue of non-null parent TreeNodes waiting to receive left and right children. queue: deque[TreeNode] = deque([root]) idx = 1 total = len(raw_root) while queue and idx < total: parent = queue.popleft() # Check `is not None` explicitly because 0 is a valid node value. if idx < total and raw_root[idx] is not None: parent.left = TreeNode(raw_root[idx]) queue.append(parent.left) idx += 1 if idx < total and raw_root[idx] is not None: parent.right = TreeNode(raw_root[idx]) queue.append(parent.right) idx += 1 return root- Create
Why iterative integer parent links beat naive recursion
Look at two key constraints in the problem statement:
- The tree can contain up to
100,000nodes. If all100,000nodes form a skewed chain (0 -> 1 -> 2 -> ... -> 99999), Python's default recursion limit (1,000stack frames) will crash any plain recursive traversal withRecursionError. - Every node value is a distinct integer. That lets us store parent links in a simple integer dictionary
parent_of: Dict[int, Optional[int]]({10: None, 4: 10, 7: 10, ...}) instead of hashing node objects!
Using an explicit
stacklist to populateparent_ofgives us zero recursion-depth risk, works even if a caller passes unhashable@dataclassnodes, and makes every ancestor step easy to trace by value.- The tree can contain up to
Record parent values until both `p` and `q` are found
Start
stack = [tree_root]andparent_of = {tree_root.val: None}. In each step of iterative depth-first search (DFS) (exploring branches via an explicit stack):- Pop
nodeand markfound_p = Trueifnode.val == p(orfound_q = Trueifnode.val == q). - For each non-null child (
node.left,node.right), recordparent_of[child.val] = node.valand pushchildontostack. - Stop as soon as both
found_pandfound_qareTrue— once both targets have been visited, their entire ancestor chains back to the root are already inparent_of!
parent_of: Dict[int, Optional[int]] = {tree_root.val: None} stack: List[Any] = [tree_root] found_p = False found_q = False while stack and not (found_p and found_q): node = stack.pop() if node.val == p: found_p = True if node.val == q: found_q = True if node.left is not None: parent_of[node.left.val] = node.val stack.append(node.left) if node.right is not None: parent_of[node.right.val] = node.val stack.append(node.right)- Pop
Intersect the two upward ancestor chains
Now two short
whileloops find the LCA:- Collect
p's ancestors: Startcurr = pand followcurr = parent_of[curr]up toNone, adding every integer visited (includingpitself!) to a hash setancestors_of_p. Always writewhile curr is not None:(neverwhile curr:), because0is a valid node value! - Climb from
quntil hitting the set: Startcurr_q = qand step upwardcurr_q = parent_of[curr_q]whilecurr_q not in ancestors_of_p. Becauseq's path walks strictly from deepest to shallowest andtree_root.valis inancestors_of_p, the first value inancestors_of_pthatcurr_qreaches is the lowest common ancestor.
Trace on Example 1 (p = 15, q = 9) and Example 2 (p = 4, q = 6): parent_of = {10: None, 4: 10, 7: 10, 12: 4, 2: 4, 9: 7, 15: 2, 6: 2} Example 1 (p = 15, q = 9): ancestors_of_p (from 15 up): {15, 2, 4, 10} climb from q = 9: curr_q = 9 -> in {15, 2, 4, 10}? No -> parent_of[9] = 7 curr_q = 7 -> in {15, 2, 4, 10}? No -> parent_of[7] = 10 curr_q = 10 -> in {15, 2, 4, 10}? Yes -> return 10 Example 2 (p = 4, q = 6): ancestors_of_p (from 4 up): {4, 10} climb from q = 6: curr_q = 6 -> in {4, 10}? No -> parent_of[6] = 2 curr_q = 2 -> in {4, 10}? No -> parent_of[2] = 4 curr_q = 4 -> in {4, 10}? Yes -> return 4- Collect
Complete solution
from collections import deque from typing import Any, Dict, List, Optional, Set, Tuple class TreeNode: """Binary tree node constructed from the serialized level-order input list.""" def __init__( self, val: int, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None, ) -> None: self.val = val self.left = left self.right = right def _build_tree(raw_root: Any) -> Optional[TreeNode]: """Convert a level-order list like [10, 4, 7, None, 9] (or an existing node) into a TreeNode root.""" if raw_root is None: return None # Support callers that pass an already-constructed node object directly. if not isinstance(raw_root, (list, tuple)): return raw_root if not raw_root or raw_root[0] is None: return None root = TreeNode(raw_root[0]) # queue: FIFO queue of non-null parent TreeNodes waiting to receive left and right children. queue: deque[TreeNode] = deque([root]) idx = 1 total = len(raw_root) while queue and idx < total: parent = queue.popleft() # Check `is not None` explicitly because 0 is a valid node value. if idx < total and raw_root[idx] is not None: parent.left = TreeNode(raw_root[idx]) queue.append(parent.left) idx += 1 if idx < total and raw_root[idx] is not None: parent.right = TreeNode(raw_root[idx]) queue.append(parent.right) idx += 1 return root def lowestCommonAncestorValue(root: Any, p: int, q: int) -> int: tree_root = _build_tree(root) if tree_root is None: raise ValueError("Tree must contain at least two nodes.") # Because all node values are unique ints, map child_val -> parent_val (None for the root), # e.g. {10: None, 4: 10, 7: 10}. Keying by int works even if input nodes are unhashable dataclasses. parent_of: Dict[int, Optional[int]] = {tree_root.val: None} # stack: explicit DFS stack of node pointers so 100,000-node chains never hit RecursionError. stack: List[Any] = [tree_root] found_p = False found_q = False # Phase 1: Traverse the tree until both target values p and q have been located. while stack and not (found_p and found_q): node = stack.pop() if node.val == p: found_p = True if node.val == q: found_q = True if node.left is not None: parent_of[node.left.val] = node.val stack.append(node.left) if node.right is not None: parent_of[node.right.val] = node.val stack.append(node.right) # Phase 2: Climb from p up to the root, recording p and every ancestor value above p. # Use `curr is not None` (never `while curr:`) so node value 0 is not treated as None! ancestors_of_p: Set[int] = set() curr: Optional[int] = p while curr is not None: ancestors_of_p.add(curr) curr = parent_of[curr] # Phase 3: Climb upward from q; the first value in ancestors_of_p is the lowest common ancestor. curr_q: Optional[int] = q while curr_q is not None and curr_q not in ancestors_of_p: curr_q = parent_of[curr_q] assert curr_q is not None return curr_q✅ Submit now — all tests should pass.
Intuition & how it works
Think of a binary tree like a family lineage chart descending from one founder at the top: to locate the lowest common ancestor (LCA) (the deepest node in the tree whose subtree holds both p and q, treating every node as its own ancestor), imagine highlighting p and every ancestor straight up to the founder, then starting at q and walking upward one generation at a time. The very first highlighted ancestor you step onto is guaranteed to be the deepest ancestor shared by both targets.
Why do simpler shortcuts fail here? First, this is an arbitrary binary tree rather than a binary search tree (BST) (a tree where left descendants are smaller and right descendants are larger), so comparing p and q against node.val tells us nothing about which branch holds them. Second, checking "does this node's subtree contain both p and q?" from scratch at every node along the path wastes O(N^2) time on skewed trees, and plain Python recursion crashes with RecursionError when 100,000 nodes form a single chain deeper than Python's 1,000-frame call-stack limit.
Because the judge can pass root as a level-order serialized list (a flat list listing nodes top-to-bottom and left-to-right, omitting children of None entries), we first run deserialization (reconstructing TreeNode objects with .left and .right pointers using a queue), then run iterative depth-first search (DFS) (exploring nodes with an explicit stack list) to record parent_of[child.val] = node.val using each node's unique integer value:
- On Example 2 ([10, 4, 7, 12, 2, None, 9, None, None, 15, 6], p = 4, q = 6), _build_tree links 10 -> (4, 7), 4 -> (12, 2), 7 -> (None, 9), and 2 -> (15, 6).
- The DFS stack records integer parent links (parent_of[4] = 10, parent_of[2] = 4, parent_of[6] = 2, ...) and stops once both 4 and 6 are located.
- Walking upward from 4 puts {4, 10} into ancestors_of_p; walking upward from 6 visits 6 -> 2 -> 4, hits 4 in {4, 10}, and returns 4.
Complexity
Let N be the number of nodes in the binary tree (L entries in the input list, where L <= 2N + 1).
- Time:
O(N). Deserializing the level-order list pops each of theNnodes from thedequeonce (O(N)). Iterative DFS pushes and pops each node at most once withO(1)dictionary insertions (O(N)), and the two upward climbs frompandqeach take at mostNsteps withO(1)average hash-set lookups (O(N)). - Space:
O(N). The constructedTreeNodeobjects, theparent_ofdictionary, the DFSstack, andancestors_of_peach store at mostNentries (O(N)total memory).
Edge cases
- One target is an ancestor of the other (
p = 4, q = 6orp = 6, q = 4): Becauseancestors_of_pstarts by addingpitself (andcurr_qchecks membership before stepping toparent_of[curr_q]), both orderings return4. - Two-node tree (
root = [8, -2], p = -2, q = 8):tree_rootitself is one of the targets, andancestors_of_p = {-2, 8}matches immediately whencurr_qstarts at8. - Deep skewed chain (
N = 100,000nodes in a single line): Both_build_tree(usingdeque) and the DFS traversal (usingstack) are iterative, so Python's recursion limit is never touched. - Sparse level-order lists with
Nonebranches ([10, 20, None, None, 30, 40, 50]): Using a queue during_build_treerather than heap-index formulas (2 * i + 1,2 * i + 2) attaches40and50under30even though10's right child wasNone. - Zero and negative boundary values (
-10^9,0,10^9): Checkingis not Noneexplicitly both in_build_treeand inwhile curr is not None:ensures node value0is never mistaken forNone. - Unhashable pre-built node objects (such as
@dataclassnodes): Keyingparent_ofandancestors_of_pby integer.valrather than node instances avoidsTypeError: unhashable type.
Common mistakes
- Treating the input list as a complete binary heap (
left = 2*i + 1, right = 2*i + 2): Standard tree serialization omits children ofNonenodes;2*i + 1indexing misplaces every node below the firstNonegap and goes out of bounds on skewed trees. - Writing
if raw_root[idx]:orwhile curr:instead ofis not None: In Python,0is falsy! Truthiness checks silently drop any node whose value is0or abort the ancestor climb early at0. - Forgetting to include
pinancestors_of_p(or steppingcurr_qbefore checking): Excludingporqfrom its own ancestor chain returns the strict parent abovepinstead ofpwhenqlies insidep's subtree. - Using unguarded recursion on
N <= 100,000: Recursive tree traversal hitsRecursionErrorwhenever tree height exceeds ~1,000.
Alternative approaches
- Bottom-up postorder DFS (
O(N)time,O(H)stack space on pointer trees): In a postorder traversal (visiting both left and right children before combining results at the parent), each subtree returnsnodeifnode.val in (p, q), bubbles up a single non-null child answer, or returnsnodeas the LCA when both left and right subtrees return non-null. Simulated iteratively with(node, visited_children)stack frames, this avoids buildingparent_ofand usesO(H)auxiliary space, whereHis the tree height.
Follow-up questions
- How would you adapt the algorithm if one or both target values might be absent from the tree and you should return None in that case? With our iterative parent-map search, you only add one check right after Phase 1:
if not (found_p and found_q): return None! By contrast, classic single-pass recursive postorder returnspimmediately upon seeingpwithout exploringp's subtree, so it would falsely returnpeven whenqis absent unless modified to search the whole tree and count how many targets were found. - If nodes already store parent pointers and you receive direct references to both target nodes, how can you find their lowest common ancestor in O(1) auxiliary space? Use the two-runner intersection trick: set
a = node_pandb = node_q, and at each step advancea = a.parent if a is not None else node_qandb = b.parent if b is not None else node_puntila is b. Ifphas depthd_pandqhas depthd_q, both runners walk the exact same total distanced_p + d_q - d_lcabefore meeting at the LCA inO(H)time andO(1)memory. - How would you preprocess a static 100,000-node tree to answer 100,000 lowest-common-ancestor queries quickly? Preprocess the tree once in
O(N log N)time and space using binary lifting (precomputingup[node][k], the2^k-th ancestor ofnodefork = 0 .. 17, alongside each node'sdepth), so each query equalizes depths and jumps upward in powers of two inO(log N)time; alternatively, reducing LCA to Range Minimum Query (RMQ) (finding the minimum element in an array subarray) over an Euler tour (the array of node depths recorded while walking around the tree) answers each query inO(1)time afterO(N log N)table setup.
Follow-up questions
- How would you adapt the algorithm if one or both target values might be absent from the tree and you should return None in that case?
- If nodes already store parent pointers and you receive direct references to both target nodes, how can you find their lowest common ancestor in O(1) auxiliary space?
- How would you preprocess a static 100,000-node tree to answer 100,000 lowest-common-ancestor queries quickly?
Similar questions
- Multi-Head Attention Forward Pass in NumPy
- Dot Product of Run-Compressed Vectors
- Mutual-Friend Recommendation
- Exact Deterministic K-Means Clustering
- Single-Output Linear Layer Gradients
- Deterministic Reservoir Sampling from Pre-Recorded Draws
More Meta interview questions
- Bipedal Dinosaur Speed Leaderboard Medium
- Balance Parentheses with Fewest Deletions Medium
- Palindrome Check Under a Deletion Budget Medium Pro
- Moving Averages Over Fixed-Width Subarrays Easy Pro
- Merge Two Sorted Lists of Disjoint Intervals Medium Pro
- Mutual-Friend Recommendation Medium Pro
- Daily Active Ad Revenue by Source Easy Pro
- Subarray Sum Existence with Negatives Medium Pro
- Shortest Maze Path with Keys and Doors Medium Pro
- Multi-Stage Stateful In-Memory Service Simulations Easy Pro