情况 1: 若 p 和 q 都在以 root 为根的树, 则 left 和 right 一定分别是 p 和 q。 情况 2: 若 p 和 q 都不在以 root 为根的树, 则直接返回 null。 情况 3: 若 p 和 q 只有一个存在于 root 为根的树, 则返回该节点。 */ classSolution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){ // base case if (!root) returnnullptr; if (root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q); TreeNode* right = lowestCommonAncestor(root->right, p, q); // case 1 if (left != nullptr && right != nullptr) { return root; } // case 2 if (left == nullptr && right == nullptr) { returnnullptr; } // case 3 return left == nullptr ? right : left; } };