class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
p_father.clear();
q_father.clear();
findFather(root, p, 0);
findFather(root, q, 1);
for (int i = 0; i < p_father.size(); i++) {
for (int j = 0; j < q_father.size(); j++) {
if (p_father[i] == q_father[j])
return p_father[i];
}
}
}
private:
vector<TreeNode*> p_father;
vector<TreeNode*> q_father;
bool findFather(TreeNode* root, TreeNode* target, bool p0Orq1) {
if (root != nullptr) {
if (root == target) {
if (p0Orq1) q_father.push_back(root);
else p_father.push_back(root);
return true;
}
bool leftFound = findFather(root->left, target, p0Orq1);
if (leftFound) {
if (p0Orq1) q_father.push_back(root);
else p_father.push_back(root);
return true;
}
bool rightFound = findFather(root->right, target, p0Orq1);
if (rightFound) {
if (p0Orq1) q_father.push_back(root);
else p_father.push_back(root);
return true;
}
}
return false;
}
};