LeetCode 236_ 二叉树的最近公共祖先

class Solution {
public:
    vector<TreeNode*> path1,path2;
    bool dfs(TreeNode* root,TreeNode* p,vector<TreeNode*>& path)
    {
        if(!root)   return false;
        if(root==p||dfs(root->left,p,path)||dfs(root->right,p,path))
        {
            path.push_back(root);
            return true;
        }
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root,p,path1);
        dfs(root,q,path2);
        reverse(path1.begin(),path1.end());
        reverse(path2.begin(),path2.end());
        TreeNode* res;
        for(int i=0;i<path1.size()&&i<path2.size();i++)
            if(path1[i]==path2[i])   res=path2[i];
        return res;
    }
};
posted @   穿过雾的阴霾  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2022-06-02 《操作系统》磁盘管理——SCAN电梯法算法c++实现
2022-06-02 《操作系统》磁盘管理——SSTF最短寻道时间优先算法c++实现
2022-06-02 《操作系统》磁盘管理——FCFS先来先服务算法c++实现
点击右上角即可分享
微信分享提示