题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <stack>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
std::vector<int> v1, v2;
auto tp = [](auto&& tp, TreeNode* n, auto& q, const auto& v) -> bool {
if (not n) return false;
if(n->val == v) return true;
if(tp(tp, n->left, q, v)) {
q.push_back(n->left->val);
return true;
} else if(tp(tp, n->right, q, v)) {
q.push_back(n->right->val);
return true;
}
return false;
};
tp(tp, root, v1, o1);
tp(tp, root, v2, o2);
// TODO: 糟糕设计:最后需要补树根
v1.push_back(root->val);
v2.push_back(root->val);
for(const auto& e1 : v1) {
for(const auto& e2 : v2) {
if(e1 == e2) return e1;
}
}
__builtin_unreachable();
}
};