二叉树的最近公共祖先
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190702191303308.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW9ob3V0YW8=,size_16,color_FFFFFF,t_70)
class Solution {
public:
vector<TreeNode*> path;
vector<vector<TreeNode*>> result;
int flag_1 = false;
int flag_2 = false;
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//首先先求出二叉树到根节点的路径,都是深度遍历的变体方法
lujing(root, p, flag_1);
lujing(root, q, flag_2);
//进行下一步
vector<TreeNode*> path_1 = result[0];
vector<TreeNode*> path_2 = result[1];
int min_len = min(path_1.size(), path_2.size());
TreeNode* shuchu =NULL;
for (int i = 0; i<min_len; ++i)
{
if (path_1[i] == path_2[i])
shuchu = path_1[i];
}
return shuchu;
}
void lujing(TreeNode* root, TreeNode*target, int &flag)
{
if (root == NULL || flag == true)
return;
path.push_back(root);
if (root == target)
{
result.push_back(path);
flag = true;
}
lujing(root->left, target, flag);
lujing(root->right, target, flag);
path.pop_back();
}
};
![在这里插入图片描述](https://img-blog.csdnimg.cn/2019070219142330.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW9ob3V0YW8=,size_16,color_FFFFFF,t_70)