零标题:算法(leetcode,附思维导图全部解法)300题之(236)二叉树的最近公共祖先 一题目描述 二解法总览(思维导图) 思维导图 三全部解法1方案1 1)代码:方案1自己。递归存储所有路径法。思路:1)状态初始化:resList〔〕,curPpath〔〕;。2)调用递归函数。3)核心:依次从底下往上找p、q的公共祖先。varlowestCommonAncestorfunction(curRoot,p,q){递归函数vardfsfunction(curPath,curRroot){const{left,right}curRcurPath。push(curRroot);1)递归出口。if(leftnullrightnull){resList。push(curPath。slice());}2)递归主体。if(leftnullright!null){dfs(curPath,right);curPath。pop();}elseif(left!nullrightnull){dfs(curPath,left);curPath。pop();}else{dfs(curPath,left);curPath。pop();dfs(curPath,right);curPath。pop();}}1)状态初始化:resList〔〕,curPpath〔〕;。letresList〔〕,curPath〔〕;2)调用递归函数。dfs(curPath,curRoot);3)核心:依次从底下往上找p、q的公共祖先。letppathresList。filter(itemitem。includes(p))〔0〕,qpathresList。filter(itemitem。includes(q))〔0〕;for(letippath。indexOf(p);i0;i){if(qpath。slice(0,qpath。indexOf(q)1)。includes(ppath〔i〕)){returnppath〔i〕;}}}; 2方案2 1)代码:方案2递归法。参考:1)https:leetcode。cnproblemslowestcommonancestorofabinarytreesolutionerchashudezuijingonggongzuxianbyleetc2思路:1)状态初始化:resN。2)调用递归函数dfs(root,p,q);。3)返回结果resNode。varlowestCommonAncestorfunction(root,p,q){constdfs(curRoot,p,q){1)递归出口。if(curRootnull){}2)递归主体。letinCurrentNodecurRootpcurRootq,inLeftdfs(curRoot。left,p,q),inRightdfs(curRoot。right,p,q);if((inLeftinRight)(inCurrentNode)){resNodecurR}returninLeftinRightinCurrentN}1)状态初始化:resN。letresN2)调用递归函数dfs(root,p,q);。dfs(root,p,q);3)返回结果resNode。returnresN}; 3方案3 1)代码:方案3存储父节点法。参考:1)https:leetcode。cnproblemslowestcommonancestorofabinarytreesolutionerchashudezuijingonggongzuxianbyleetc2TODO:重新手撕。思路:1)状态初始化:resParentMapnewMap(),visitedSetnewSet()。2)调用递归函数dfs(root);。3)核心处理:暂略(TODO)。varlowestCommonAncestorfunction(root,p,q){constdfs(curRrootnull){const{left,right}curRif(left!null){resParentMap。set(left。val,curRroot);dfs(left);}if(right!null){resParentMap。set(right。val,curRroot);dfs(right);}};1)状态初始化:resParentMapnewMap(),visitedSetnewSet()。letresParentMapnewMap(),visitedSetnewSet();2)调用递归函数dfs(root);。dfs(root);3)核心处理:暂略(TODO)。while(p!null){visitedSet。add(p。val);presParentMap。get(p。val);}while(q!null){if(visitedSet。has(q。val)){}qresParentMap。get(q。val);}} 四资源分享更多1历史文章总览 历史文章总览 刷题进度LeetCode:5262662、《剑指offer》:6666 2博主简介 码农三少,一个致力于编写极简、但齐全题解(算法)的博主。专注于一题多解、结构化思维,欢迎一起刷穿LeetCode