/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param p int整型
* @param q int整型
* @return int整型
*/
int lowestCommonAncestor(TreeNode* root, int p, int q) {
// write code here
if(p<root->val && q<root->val)
return lowestCommonAncestor(root->left, p, q);
if (p>root->val && q>root->val)
return lowestCommonAncestor(root->right, p, q);
return root->val;
}
};
根据二叉搜索树的性质:
- 如果p和q均小于root的val,那么最近公共祖先必然在root左子树
- 如果p和q均大于root的val,那么最近公共祖先必然在root右子树
- 如果p,q一个大于一个小于,那么最近公共祖先就是root(也包含了p,q自身)

京公网安备 11010502036488号