直接递归,思路清晰
class Solution {
public:
int lowestCommonAncestor(TreeNode* root, int p, int q) {
int Min = min(p, q);
int Max = max(p, q);
if (root->val > Min && root->val > Max) {
return lowestCommonAncestor(root->left, p, q);
}
if (root->val < Min && root->val < Max) {
return lowestCommonAncestor(root->right, p, q);
}
return root->val;
}
};

京公网安备 11010502036488号