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;

    }
}
相关推荐
alphaTao18 小时前
LeetCode 每日一题 2026/7/20-2026/7/26
算法·leetcode
圣保罗的大教堂19 小时前
leetcode 3514. 不同 XOR 三元组的数目 II 中等
leetcode
青山木1 天前
Hot 100 ---腐烂的橘子
java·数据结构·后端·算法·leetcode·广度优先
xqqxqxxq1 天前
LeetCode Hot100 双指针专项题解笔记
笔记·算法·leetcode
闪电悠米1 天前
力扣hot100-54.螺旋矩阵-模拟边界控制详解
算法·leetcode·矩阵
To_OC1 天前
LC 51 N 皇后:我以为难的是回溯,结果栽在了对角线下标
javascript·算法·leetcode
闪电悠米2 天前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
过期动态2 天前
【LeetCode 热题 100】找到字符串中所有字母异位词
java·数据结构·算法·leetcode·职场和发展·rabbitmq
Adios7942 天前
设置交集大小至少为2
数据结构·算法·leetcode
程序猿乐锅3 天前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode