原题题目
代码实现(首刷大部分看解小部分自解):(
struct TreeNode* ans;
bool visit(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q)
{
if(!root)
return false;
bool left = visit(root->left,p,q);
bool right = visit(root->right,p,q);
if(root == p || root == q && (left || right) || left && right)
{
ans = root;
return true;
}
if(root == p || root == q)
return true;
return left || right;
}
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q){
if(root == q || root == p)
return root;
visit(root,p,q);
return ans;
}