面试经典题:二叉树最近公共祖先

二叉树的最近公共祖先#

面试经典题:最近公共祖先,提供三种思路:1、模拟路径,2、dfs,3、dfs优化

Copy
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; } };
Copy
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; } };
Copy
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; } };
posted @   SrtFrmGNU  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示
CONTENTS