题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: int lowestCommonAncestor(TreeNode* root, int p, int q) { if ((q > root->val && p > root->val) || (q < root->val && p < root->val)) { return lowestCommonAncestor(q > root->val ? root->right : root->left, p, q); } return root->val; } };