/**
* 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 || root == p || root == q)
return root;
TreeNode *left = lowestCommonAncestor(root->left,p,q);
TreeNode *right = lowestCommonAncestor(root->right,p,q);

if(NULL == left)
return right;
else if(NULL == right)
return left;
else
return root;
//one line judge
//return left == NULL ? right:right == NULL ? left:root;
}
};

Runtime: 16 ms, faster than 94.88% of C++ online submissions for Lowest Common Ancestor of a Binary Tree.
Memory Usage: 14.8 MB, less than 5.21% of C++ online submissions for Lowest Common Ancestor of a Binary Tree.

2021.05.25笔记

/**
* 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 == nullptr || root == p || root ==q) return root;
TreeNode * left = lowestCommonAncestor(root->left,p,q);
TreeNode * right = lowestCommonAncestor(root->right,p,q);
if(left == nullptr && right == nullptr)
return nullptr;
if(left != nullptr && right != nullptr)
return root;

return (left == nullptr) ? right:left;
}
};