Problem
Given binary-tree root and a nonempty list nodes of distinct TreeNode pointers, return the lowest existing tree node that is an ancestor of every listed node. A node is its own ancestor for this purpose. Preserve the node-pointer interface; the query supplies actual nodes belonging to this tree.
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, vector<TreeNode*> &nodes);
};
Examples
Example 1:
Tree: root 9 has children 4 and 13; node 4 has children 2 and 6.
nodes contains pointers to 2 and 6.
Output: pointer to node 4
Example 2:
Tree: root 7 has children 3 and 11.
nodes contains only the pointer to 11.
Output: pointer to node 11
Explanation: A single queried node is its own lowest common ancestor.
Constraints
-
The tree contains
1..10^4
nodes.
-
Values are unique integers in
[-10^9,10^9]
.
-
Each nodes entry exists in the tree, and query pointers are distinct.
-
For this practice version,
1 <= nodes.length <= N
, where
N
is the tree's node count.
Practice Assumptions
The query list is nonempty for this practice version. The returned pointer must identify an existing TreeNode, not merely its value.
Reasoning checkpoints
-
Show that the returned existing node is an ancestor of every requested node.
-
Prove that no proper descendant has that property, respecting the nonempty query and node identities.
Optional extensions
What preprocessing would make repeated collection-LCA queries more efficient?