简要题解:
递归解法找到两个节点分别是在左子树还是在右子树中 要是分别在左右子树中根节点即为最近公共祖先要是都在左子树即是递归返回来左节点为最近公共祖先节点,要是都在右子树跟其一致。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL)return NULL;
if(root==p||root==q)
{
return root;
}
TreeNode* left=lowestCommonAncestor(root->left,p,q);
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(left!=NULL&&right!=NULL) return root;
if(left!=NULL) return left;
if(right!=NULL)return right;
return NULL;
}
};
非递归解法
找到两个节点的简单路径后直接比较两个节点的路径即可
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool dfs(TreeNode* root,TreeNode *m,vector<TreeNode*>&pa)
{
if(root==NULL) return false;
pa.push_back(root);
if(root==m) return true;
bool flag=true;
flag=dfs(root->left,m,pa);
if(!flag)
flag=dfs(root->right,m,pa);
if(!flag)
pa.pop_back();
return flag;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode* >p1;
vector<TreeNode* >p2;
dfs(root,p,p1);
dfs(root,q,p2);
TreeNode* ans=root;
for(int i=0;i<min(p1.size(),p2.size());i++)
{
if(p1[i]==p2[i])
{
ans=p1[i];
} else break;
}
return ans;
}
};