Lowest Common Ancestor in a Binary Tree
Updated
Problem statement
You are given the root of a binary tree and two values, p and q. The tree has at least one node, every node value is unique, and both values are in the tree. Return the value of their lowest common ancestor.
An ancestor of a node is any node on the path from the root down to it. A node counts as its own ancestor. The lowest common ancestor is the deepest node whose subtree holds both target nodes. The two targets may be the same.
The tree is a general binary tree. It does not have to be a binary search tree. Do not change any links or values in the input tree.
The tree is shown in level order, with null for a missing child.
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 = 3The node holding five is in the root's left subtree, and the node holding one is in its right subtree. The only node above both of them is the root, so the answer is the root's value, three.
Example 2
root = [3,5,1,6,2,0,8,null,null,7,4]p = 5q = 4return = 5The node holding four sits inside the subtree of the node holding five. A node counts as its own ancestor, so five is the deepest node above both targets. The answer is five.
Constraints
- The tree contains between
1and20000nodes. - Node values are unique integers in
[-10^9,10^9]. - Both
pandqare existing node values.
More Apple Phone Screen questions
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Dec 2026
- Topological OrderingPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Merge IntervalsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Subarray Product Less Than KPHONE SCREEN · Seen Nov 2026
- Evaluate DivisionPHONE SCREEN · Seen Nov 2026
- Reverse a Linked ListPHONE SCREEN · Seen Nov 2026
- Validate a BST with a Custom ComparisonPHONE SCREEN · Seen Nov 2026
- Design a Food Rating SystemPHONE SCREEN · Seen Oct 2026
- Days Until Poisoned Plants StabilizePHONE SCREEN · Seen Oct 2026
- Capture Surrounded Regions with Union-FindPHONE SCREEN · Seen Oct 2026
Similar questions at other companies
- N-ary Index-Path Encoder and DecoderBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Account Roles With Parent-User InheritanceStripe · PHONE SCREENStripe interview questions
- Merge N-Ary Trees by KeyLinkedIn · PHONE SCREEN · ONSITE INTERVIEWLinkedIn interview questions
- Filesystem Hash TreeCursor · PHONE SCREEN · ONSITE INTERVIEWCursor interview questions
- Render a Stable Comment HierarchyBobyard · PHONE SCREEN
- Translate Values in a Nested MapZip · PHONE SCREENZip interview questions
- Employee Importance from a DictionaryPatreon · PHONE SCREENPatreon interview questions
- Build a Trace ForestDatadog · PHONE SCREENDatadog interview questions
- Transform and Prune a Mode-Valued Binary TreeGoogle · PHONE SCREENGoogle interview questions
- Topmost Accessible NodesFigma · PHONE SCREEN · ONSITE INTERVIEWFigma interview questions