Leetcode236.二叉树的最近公共祖先(HOT100)

链接

代码:

cpp 复制代码
class Solution {
public:
    TreeNode* ans = nullptr;
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root,p,q);
        return ans;//dfs方法会把答案写在ans中我们返回即可
    }
    int dfs(TreeNode* root,TreeNode* p,TreeNode*q){
        if(root==nullptr){
            return 0;
        }
        //我们使用state的低两位表示 p q是否有找到,比如00代表都没有找到,10代表q找到了,p没有找到
        int state = dfs(root->left,p,q);//遍历左子树找pq
        if(root==p)state|=1;//然后再看根节点
        else if(root==q)state|=2;
        state|=dfs(root->right,p,q);//然后再看右子树
        if(state==3&&ans==nullptr){//如果是3,还不能盲目更新,要看之前是否有更新过,dfs是从底层上来的,如果之前更新过,现在就不要更新了
            ans = root;
        }
        return state;
    }
};
https://www.acwing.com/video/1620/

代码二:

cpp 复制代码
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root||root==p||root==q){
            return root;
        }
        auto left = lowestCommonAncestor(root->left,p,q);
        auto right = lowestCommonAncestor(root->right,p,q);
        if(left&&right){
            return root;
        }
        if(left){
            return left;
        }
        if(right){
            return right;
        }
        return nullptr;
    }
};


https://www.bilibili.com/video/BV19t411w7Ep?t=3436.9
相关推荐
Regulus-Moon1 分钟前
凸优化:局部即全局的定价表——条件数 κ 上的速率谱系
算法·机器学习·数学建模
FPGA小迷弟8 分钟前
PID 算法全解:从历史渊源到 FPGA 硬件实现
算法·fpga开发·硬件架构·fpga·sm4
洞见新研社9 分钟前
半年从蓝海杀入红海,机器人数据生意变天了
人工智能·算法·机器人
纪念 22933 分钟前
C++ 算法模板与错题 (高精度)
开发语言·c++·算法
Navigator_Z2 小时前
LeetCode //C - 1331. Rank Transform of an Array
c语言·算法·leetcode
Tisfy2 小时前
LeetCode 1202.交换字符串中的元素:分组排序(连通图)
算法·leetcode·字符串·bfs·题解·排序·连通图
csdn_aspnet9 小时前
C++ 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
c++·算法
逐米时代11 小时前
「制造新解法」行业对标方法:借鉴而不照搬的最佳实践
人工智能·算法·制造
kyrie_sakura12 小时前
大模型学习32 --大模型微调3 -- 分布式训练算法
分布式·学习·算法
Rabitebla12 小时前
【Linux】 文件系统(五):挂载与软硬链接,多个文件系统怎样组成统一目录树
linux·运维·服务器·c++·笔记·学习·算法