面试经典题:二叉树最近公共祖先
二叉树的最近公共祖先#
面试经典题:最近公共祖先,提供三种思路:1、模拟路径,2、dfs,3、dfs优化
class Solution {
public:
bool dfs(TreeNode* root, TreeNode* t, vector<TreeNode*>&path){
if(!root) return false;
if(root == t){
path.push_back(root);
return true;
}
if(dfs(root->left,t,path) || dfs(root->right,t,path)){
path.push_back(root);
return true;
}
return false;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode*> a,b;
dfs(root, p, a);
dfs(root, q, b);
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int n=min(a.size(), b.size());
for(int i=n-1;i>=0;i--){
if(a[i] == b[i]) return a[i];
}
return NULL;
}
};
class Solution {
public:
TreeNode* ans=NULL;
int dfs(TreeNode*root, TreeNode*p, TreeNode*q){
if(!root) return 0;
int state=dfs(root->left,p,q) | dfs(root->right,p,q);
if(root==p) state|=1;
else if(root==q) state|=2;
if(state==3 && !ans) ans=root;
return state;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
dfs(root,p,q);
return ans;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || root==p || root==q) return root;
auto l=lowestCommonAncestor(root->left,p,q);
auto r=lowestCommonAncestor(root->right,p,q);
if(!l) return r;
if(!r) return l;
return root;
}
};
作者: SrtFrmGNU
出处:https://www.cnblogs.com/SrtFrmGNU/p/16120499.html
版权:本站使用「CC BY 4.0」创作共享协议,转载请在文章明显位置注明作者及出处。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具