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
相关推荐
2301_8076114933 分钟前
77. 组合
c++·算法·leetcode·深度优先·回溯
SsummerC2 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
好易学·数据结构3 小时前
可视化图解算法:二叉树的最大深度(高度)
数据结构·算法·二叉树·最大高度·最大深度·二叉树高度·二叉树深度
程序员-King.3 小时前
day47—双指针-平方数之和(LeetCode-633)
算法·leetcode
阳洞洞3 小时前
leetcode 1035. Uncrossed Lines
算法·leetcode·动态规划·子序列问题
小鹿鹿啊3 小时前
C语言编程--15.四数之和
c语言·数据结构·算法
rigidwill6664 小时前
LeetCode hot 100—最长有效括号
数据结构·c++·算法·leetcode·职场和发展
wuqingshun3141594 小时前
蓝桥杯17. 机器人塔
c++·算法·职场和发展·蓝桥杯·深度优先
图灵科竞社资讯组5 小时前
图论基础:图存+记忆化搜索
算法·图论