235. 二叉搜索树的最近公共祖先
因为二叉搜索树为有序树,所以可以判断当前结点和p,q的值来决定递归的方向,
递归法
当当前结点的值在[p,q]之间的时候,该节点就是最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL)return root;
if(root->val > p->val && root->val > q->val)
{
TreeNode* left = lowestCommonAncestor(root->left,p,q);
if(left)return left;
}
if(root->val < p->val && root->val < q->val)
{
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if(right)return right;
}
return root;
}
};
精简
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root->val > p->val && root->val > q->val) {
return lowestCommonAncestor(root->left, p, q);
} else if (root->val < p->val && root->val < q->val) {
return lowestCommonAncestor(root->right, p, q);
} else return root;
}
};
迭代法
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root) {
if (root->val > p->val && root->val > q->val) {
root = root->left;
} else if (root->val < p->val && root->val < q->val) {
root = root->right;
} else return root;
}
return NULL;
}
};