题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
/** * 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 p int整型 * @param q 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 p, int q) { Find_fother(root, -1); vector<int> num1,num2; num1.push_back(p); num2.push_back(q); while(fu[p]!=-1) { num1.push_back(fu[p]); p=fu[p]; } while(fu[q]!=-1) { num2.push_back(fu[q]); q=fu[q]; } 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; } };