/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
bool find = false; //标记是否找到了
void dfs(TreeNode* root, int target, vector<int>& t_v)
{
//已经找到或者到达空节点
if(find || !root)
return;
t_v.emplace_back(root->val);
if(root->val==target)
{
find = true;
return;
}
if(root->left)
dfs(root->left, target, t_v);
if(root->right)
dfs(root->right, target, t_v);
if(find) { //防止将节点去除
return;
}
//不在这条路径,去除节点
t_v.pop_back();
return;
}
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
// write code here
// 深度优先搜索
vector<int> v1,v2;
dfs(root,o1,v1);
// 注意重置find
find = false;
dfs(root,o2,v2);
// cout << v1.size() << ", " << v2.size() << endl;
int res=0;
for(int i=0; i<v1.size() && i<v2.size(); ++i)
{
if(v1[i]==v2[i])
res = v1[i];
else
break;
}
return res;
}
};