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

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:"对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。"

题解:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

代码如下:

java 复制代码
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == q || root == p || root == null){
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);
        if(left != null && right != null){
            return root;
        }
        if(left == null){
            return right;
        }
        return left;

    }
}
相关推荐
zstar-_8 分钟前
Claude code在Windows上的配置流程
笔记·算法·leetcode
??tobenewyorker4 小时前
力扣打卡第23天 二叉搜索树中的众数
数据结构·算法·leetcode
贝塔西塔4 小时前
一文读懂动态规划:多种经典问题和思路
算法·leetcode·动态规划
呆呆的小鳄鱼7 小时前
leetcode:HJ18 识别有效的IP地址和掩码并进行分类统计[华为机考][字符串]
算法·leetcode·华为
zstar-_7 小时前
【算法笔记】7.LeetCode-Hot100-图论专项
笔记·算法·leetcode
岁忧8 小时前
(LeetCode 面试经典 150 题 ) 209. 长度最小的子数组(双指针)
java·c++·算法·leetcode·面试·go
剪一朵云爱着14 小时前
力扣2438. 二的幂数组中查询范围内的乘积
算法·leetcode
thusloop20 小时前
380. O(1) 时间插入、删除和获取随机元素
数据结构·算法·leetcode
緈福的街口21 小时前
【leetcode】584. 寻找用户推荐人
算法·leetcode·职场和发展