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;

    }
}
相关推荐
爱coding的橙子1 天前
每日算法刷题Day84:11.11:leetcode 动态规划9道题,用时2h
算法·leetcode·动态规划
Kt&Rs1 天前
11.11 LeetCode 题目汇总与解题思路
算法·leetcode·哈希算法
py有趣1 天前
LeetCode算法学习之有效的字母异位词
学习·算法·leetcode
蒙奇D索大1 天前
【算法】递归算法的深度实践:从布尔运算到二叉树剪枝的DFS之旅
笔记·学习·算法·leetcode·深度优先·剪枝
小白程序员成长日记2 天前
2025.11.10 力扣每日一题
数据结构·算法·leetcode
dragoooon342 天前
[优选算法专题六.模拟 ——NO.40~41 外观数列、数青蛙]
数据结构·算法·leetcode
一匹电信狗2 天前
【C++】封装红黑树实现map和set容器(详解)
服务器·c++·算法·leetcode·小程序·stl·visual studio
flashlight_hi2 天前
LeetCode 分类刷题:141. 环形链表
javascript·算法·leetcode
Kt&Rs2 天前
11.9 LeetCode 题目汇总与解题思路
算法·leetcode
ゞ 正在缓冲99%…2 天前
leetcode1547.切棍子的最小成本
数据结构·算法·leetcode·动态规划