目录
- 1.题目描述
- 2.算法思路
- 2.1算法思路1
- 2.2算法思路2
- 3.代码实现
- 3.1代码实现1
- 3.2 代码实现2
1.题目描述
2.算法思路
2.1算法思路1
2.2算法思路2
思想很简单,但是最难的是怎么用栈来记录q、p的路线。所以下面才是关键。
3.代码实现
3.1代码实现1
class Solution {
public:
bool find(TreeNode* root,TreeNode* obj)
{
if(root==nullptr)
{
return false;
}
if(root->val==obj->val)
{
return true;
}
return find(root->left,obj)||find(root->right,obj);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
if(root==p||root==q)
{
return root;
}
bool pinright,pinleft,qinright,qinleft;
pinleft=find(root->left,p);
pinright=!pinleft;
qinleft=find(root->left,q);
qinright=!qinleft;
if((qinleft&&pinright)||(qinright&&pinleft))
{
return root;
}
if(qinleft&&pinleft)
{
return lowestCommonAncestor(root->left,p,q);
}
if(pinright&&qinright)
{
return lowestCommonAncestor(root->right,p,q);
}
return nullptr;
}
};
3.2 代码实现2
class Solution {
public:
bool find(TreeNode* root,TreeNode* cur,stack<TreeNode*>& path)
{
//根为空
if(root==nullptr)
{
return false;
}
//根入栈
path.push(root);
//根即为所求
if(root==cur)
{
return true;
}
//递归去左子树 如果左子树找到了就返回true
if(find(root->left,cur,path))
{
return true;
}
//递归去右子树 如果右子树找到就返回true
if(find(root->right,cur,path))
{
return true;
}
//左子树右子树都没找到 pop根 返回false
path.pop();
return false;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
stack<TreeNode*> ppath;
stack<TreeNode*> qpath;
find(root,p,ppath);
find(root,q,qpath);
while(ppath.size()>qpath.size())
{
ppath.pop();
}
while(qpath.size()>ppath.size())
{
qpath.pop();
}
while(ppath.size())
{
if(ppath.top()==qpath.top())
{
return ppath.top();
}
ppath.pop();
qpath.pop();
}
return nullptr;
}
};