一、236. 二叉树的最近公共祖先
/**
* 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) {
// 判断一个节点左子树右子树是否同时包含pq即可
if(root==p||root==q||root==NULL) return root;
TreeNode * left = lowestCommonAncestor(root->left,p,q);
TreeNode * right = lowestCommonAncestor(root->right,p,q);
if(left!=NULL&&right!=NULL) return root;
else if(left!=NULL&&right==NULL) return left;
else if(left==NULL&&right!=NULL) return right;
else return NULL;
}
};
二、235. 二叉搜索树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 判断一个节点左子树右子树是否同时包含pq即可
if(root==p||root==q||root==NULL) return root;
TreeNode * left = lowestCommonAncestor(root->left,p,q);
TreeNode * right = lowestCommonAncestor(root->right,p,q);
if(left!=NULL&&right!=NULL) return root;
else if(left!=NULL&&right==NULL) return left;
else if(left==NULL&&right!=NULL) return right;
else return NULL;
}
};