class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* cur, TreeNode* p, TreeNode* q) {
if (cur == NULL) return cur; //中
if (cur->val > p->val && cur->val > q->val) { //向左遍历
TreeNode* left = lowestCommonAncestor(cur->left, p ,q);
if (left != NULL) {
return left;
}
}
if (cur->val < p->val && cur->val < q->val) { //向右遍历
TreeNode* right = lowestCommonAncestor(cur->right, p, q);
if (right != NULL) {
return right;
}
}
return cur;
}
};
时间复杂度:O(n)
思路:因为是二叉搜索树,所以它是有序的,所以不需要进行后序遍历,用回溯的思想,而是可以直接先序遍历,直到找到满足条件的那条边,即找到最近公共祖先,而公共祖先满足的条件就是cur的val在p的val和val之间即可,但是前提条件是从上到下开始遍历,所以用到先序遍历。
精简版
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* cur, TreeNode* p, TreeNode* q) {
if (cur->val > p->val && cur->val > q->val)
return lowestCommonAncestor(cur->left, p, q);
else if (cur->val < p->val && cur->val < q->val)
return lowestCommonAncestor(cur->right, p, q);
else return cur;
}
};