剑指 Offer 68 - I 二叉搜索树的最近公共祖先
概述
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
递归法
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root->val == p->val || root->val == q->val) return root;
if (root->val > p->val != root->val > q->val) return root;
if (root->val > p->val) return lowestCommonAncestor(root->left, p, q);
else return lowestCommonAncestor(root->right, p, q);
}
};
Links: sword-offer-68-1