235. 二叉搜索树的最近公共祖先
每日链接

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
return root

C++
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p->val < root->val && q->val < root->val){
return lowestCommonAncestor(root->left, p, q);
}
else if (p->val > root->val && q->val > root->val){
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
};