Posted on

Description

Submission

/**
 * 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 {
    unordered_set<TreeNode*> nodeSet;
    TreeNode* ret = nullptr;

    int lca(TreeNode* root) {
        if(!root) return 0;
        int count = lca(root->left) + lca(root->right) + (nodeSet.find(root) != nodeSet.end());
        if(count == nodeSet.size() && !ret) ret = root;
        return count;
    }
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, vector<TreeNode*> &nodes) {
        for(auto node: nodes) {
            nodeSet.insert(node);
        }

        lca(root);

        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *