Skip to main content
Back to problems
#1676
Medium Algorithms

Lowest common ancestor of a binary tree iv

Hash Table Tree Depth-First Search Binary Tree
79.6% acceptance
Mar 31, 2026
504
16
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 p1, p2, ..., pn in a binary tree T is the lowest node that has every pi 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.

Solution

C++
Time O(n)
Space O(n)
LeetCode
solution.cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  TreeNode* lowestCommonAncestor(TreeNode* root, vector<TreeNode*>& nodes) {
    unordered_set<TreeNode*> nodeSet(nodes.begin(), nodes.end());
    return dfs(root, nodeSet);
  }
  
  TreeNode* dfs(TreeNode* root, unordered_set<TreeNode*>& nodeSet) {
    if (!root || nodeSet.count(root)) return root;
    TreeNode* left = dfs(root->left, nodeSet);
    TreeNode* right = dfs(root->right, nodeSet);
    if (left && right) return root;
    return left ? left : right;
  }
};