思路
从两个叶子节点往父节点找,后序遍历很适合。注意递归逻辑中的四个逻辑判断。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == q || root == p || root == nullptr) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != nullptr && right != nullptr) return root;
if (left == nullptr && right == nullptr) return nullptr;
if (left == nullptr && right != nullptr) return right;
else return left;
}
};