文章目录
1 题目
2 解析
2.1 法1
节点ancestor
从根节点向下遍历,
- 如果
ancestor->val
同时小于q->val
和p-val
,那么公共祖先就在ancestor
的右边; - 如果
ancestor->val
同时大于q->val
和p-val
,那么公共祖先就在ancestor
的左边; - 如果
ancestor->val
不同时小于或大于q->val
和p-val
,那么它就是分岔节点(即两个节点的公共祖先);
2.2 法2
同时遍历根节点到q
、p
的路径,公共祖先节点就是路径上最后一个相同的节点。
2.2 法2
3 代码
3.1
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode* ancestor = root;
while (true){
if(p->val < ancestor->val && q->val < ancestor->val){
ancestor = ancestor->left;
}else if(p->val > ancestor->val && q->val > ancestor->val){
ancestor = ancestor->right;
}else{
break;
}
}
return ancestor;
}
};
3.2 代码
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
auto getPath = [](TreeNode* root, TreeNode* target){
auto func = [&](auto && self, TreeNode* root, TreeNode* target){
vector<TreeNode*> path;
TreeNode* node = root;
while(node != target){
path.emplace_back(node);
if(target->val > node->val){
node = node->right;
}else{
node = node->left;
}
}
path.emplace_back(node);
return path;
};
return func(func, root, target);
};
vector<TreeNode*> pPath = getPath(root, p);
vector<TreeNode*> qPath = getPath(root, q);
TreeNode* ancestor;
for(int i = 0;i < pPath.size() && i < qPath.size();i++){
if(pPath[i] == qPath[i]){
ancestor = pPath[i];
}else{
break;
}
}
return ancestor;
}
};