思路:
得到左右子树的p、q的最近公共祖先
left、right
11,在root异侧,返回root
01,在root左侧,返回left
10,在root右侧,返回right
00,两侧都没有,返回NULL
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL||root==p||root==q) return root;
TreeNode* left=lowestCommonAncestor(root->left,p,q);
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(left&&right) return root;
else if(!left&&right) return right;
else if(left&&!right) return left;
else return NULL;
}
};