MMicrosoft·DSASDE-1Onsite – Coding 1
Lowest Common Ancestor of a Binary Tree
Problem
Given a binary tree and two nodes p and q, return their Lowest Common Ancestor (LCA).
The LCA is the deepest node that has both p and q as descendants (a node can be a descendant of itself).
Example
3
/ \
5 1
/ \ / \
6 2 0 8
LCA(5, 1) = 3
LCA(5, 6) = 5
Follow-up variants asked at Microsoft
- LCA in a Binary Search Tree (can you do it without recursion?)
- LCA when parent pointers are available
- LCA with multiple query pairs — how do you preprocess for O(log n) per query?
added 6 days ago