https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
递归实现最近公共祖先,函数返回该子树是否包含p,q。有两种情况,1.p、q在同一条路径上,所以需要找到了p或者q继续向下查找,找到了了的话最近公共祖先就是这个。2.p,q在两条支路上,那么最近公共祖先的左右子树各包含pq。
/**
* 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* ans;
bool find(TreeNode* root, TreeNode* p, TreeNode* q){
if(root==NULL)
return false;
if(root==p||root==q){
bool ret1=find(root->left,p,q);
bool ret2=find(root->right,p,q);
if(ret1||ret2){
ans=root;
}
return true;
}
else{
bool ret1=find(root->left,p,q);
bool ret2=find(root->right,p,q);
if(ret1&&ret2)
ans=root;
return ret1||ret2;
}
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
ans=NULL;
find(root,p,q);
return ans;
}
};
这个是求父节点和深度版本的。
/**
* 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:
map<TreeNode*,TreeNode*> father;
map<TreeNode*,int> depth;
void get_father(TreeNode *root,int d){
if(root==NULL)
return;
depth[root]=d;
if(root->left){
father[root->left]=root;
}
if(root->right)
father[root->right]=root;
get_father(root->left,d+1);
get_father(root->right,d+1);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
get_father(root,0);
int depth_p=depth[p];
int depth_q=depth[q];
if(depth_p<depth_q){//p more depth
swap(depth_p,depth_q);
swap(p,q);
}
while(depth_p>depth_q){
p=father[p];
depth_p--;
}
while(p!=q){
p=father[p];
q=father[q];
}
return p;
}
};