1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (!root) return nullptr; if (!p || !q) return root; auto [s, l] = minmax(p->val, q->val); if (s <= root->val && root->val <= l) return root; if (root->val < s) return lowestCommonAncestor(root->right, p, q); if (l < root->val) return lowestCommonAncestor(root->left, p, q); return nullptr; } };
|