Lowest Common Ancestor in a Binary Tree
Updated
Problem statement
You are given the root of a binary tree with unique integer values and two values p and q that occur in the tree.
Return the value of their lowest common ancestor: the deepest node whose subtree contains both target nodes. A node is considered an ancestor of itself.
Function
lowestCommonAncestorValue(root: TreeNode, p: int, q: int) → intExamples
Example 1
root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 1return = 3Nodes 5 and 1 lie in different subtrees of the root.
Example 2
root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 4return = 5Node 5 is an ancestor of node 4 and may be the answer itself.
Example 3
root = [1,2]p = 1q = 2return = 1The root is one of the targets.
Constraints
- The tree contains between
2and2000nodes. - All node values are unique signed 32-bit integers.
p != q, and both values occur in the tree.
More Google Phone Screen questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Periodic-Color Binary Forest RootsPHONE SCREEN · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Stock Trade with Buy and Sell DaysPHONE SCREEN · Seen Nov 2026
- Word Chain Jumps in a GridPHONE SCREEN · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
- Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
- Course Schedule Cycle DetectionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Binary Tree Target-Sum PathsByteDance · PHONE SCREENByteDance interview questions
- Count Uni-Valued SubtreesAmazon · PHONE SCREEN
- Validate Binary Search TreeLyft · PHONE SCREENLyft interview questions
- Check Whether a Tree Is a Sum TreeAdobe · PHONE SCREENAdobe interview questions
- Lowest Common Ancestor in a Binary TreeZillow · PHONE SCREENZillow interview questions
- Maximum Value in a Binary TreeAkuna Capital · PHONE SCREENAkuna Capital interview questions
- Sum Root-to-Leaf NumbersMeta · ONSITE INTERVIEWMeta interview questions
- Validate Binary Search TreeGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Balanced Tree Node ReportNetflix · ONSITE INTERVIEWNetflix interview questions
- Trim a Binary Search TreeBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions