题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
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) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
map<int,int> fu;
void Find_fother(TreeNode* root,int f)
{
if(root==nullptr)
return;
fu[root->val]=f;
Find_fother(root->left, root->val);
Find_fother(root->right, root->val);
}
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
Find_fother(root, -1);
vector<int> num1,num2;
num1.push_back(o1);
num2.push_back(o2);
while(fu[o1]!=-1)
{
num1.push_back(fu[o1]);
o1=fu[o1];
}
while(fu[o2]!=-1)
{
num2.push_back(fu[o2]);
o2=fu[o2];
}
for(int i=0;i<num1.size();i++)
for(int j=0;j<num2.size();j++)
if(num1[i]==num2[j])
return num1[i];
return 0;
}
};
360集团公司氛围 347人发布