Lowest Common Ancestor of a Binary Tree IV Problem
Description
LeetCode Problem 1676.
Given the root of a binary tree and an array of TreeNode objects nodes, return the lowest common ancestor (LCA) of all the nodes in nodes. All the nodes will exist in the tree, and all values of the tree's nodes are unique.
Extending the definition of LCA on Wikipedia: "The lowest common ancestor of n nodes p_1, p_2, ..., p_n in a binary tree T is the lowest node that has every p_i as a descendant (where we allow a node to be a descendant of itself) for every valid i". A descendant of a node x is a node y that is on the path from node x to some leaf node.
Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [4,7]
Output: 2
Explanation: The lowest common ancestor of nodes 4 and 7 is node 2.
Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [1]
Output: 1
Explanation: The lowest common ancestor of a single node is the node itself.
Example 3:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [7,6,2,4]
Output: 5
Explanation: The lowest common ancestor of the nodes 7, 6, 2, and 4 is node 5.
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. -10^9 <= Node.val <= 10^9- All
Node.valare unique. - All
nodes[i]will exist in the tree. - All
nodes[i]are distinct.
Solution
Approach: DFS With a Set of Targets
This generalises the two-node LCA. Put the values of all nodes in a hash set, then run a DFS that returns, for each subtree, the topmost target node found in it (or null if there is none):
- If the current node is
nullor is one of the targets, return it. A target's descendants do not matter, because the target itself is already an ancestor of any targets below it. - Otherwise search both children. If both return a node, targets lie on both sides and the current node is the LCA. If only one side returns a node, pass that result up.
The value returned for the root is the answer.
Complexity: O(n + m) time and O(n + m) space for the set and the recursion, where n is the number of tree nodes and m is the length of nodes.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(
self, root: 'TreeNode', nodes: 'List[TreeNode]'
) -> 'TreeNode':
def dfs(root):
if root is None or root.val in s:
return root
left, right = dfs(root.left), dfs(root.right)
if left and right:
return root
return left or right
s = {node.val for node in nodes}
return dfs(root)