二叉树的最近公共祖先
p和q的位置关系:p和q分居root两侧;p和q在root的左侧或者右侧。先遇到谁就返回谁。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == p || root == q) return root; //先遇到谁就返回谁
//先到root的两侧进行寻找
TreeNode* l = lowestCommonAncestor(root->left,p,q);
TreeNode* r = lowestCommonAncestor(root->right,p,q);
if(r != nullptr && l != nullptr){ //说明p和q分居root两侧
return root;
}else{
return l == nullptr ? r : l;
}
}
};
二叉搜索树:根节点比左孩子大,比右孩子小。
根据二叉搜索树的特性,可以进行比较来判断p和q的位置关系。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == p || root == q) return root;
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);
}else{//p和q分居root两侧
return root;
}
}
};