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;

    }
}
相关推荐
0+1112 小时前
算法 --滑动窗口
c++·算法·leetcode
木井巳3 小时前
【记忆化搜索】最长递增子序列
java·算法·leetcode·深度优先·剪枝·推荐算法
圣保罗的大教堂5 小时前
leetcode 1401. 圆和矩形是否有重叠 中等
leetcode
hanlin036 小时前
刷题笔记:力扣第76题-最小覆盖子串
笔记·算法·leetcode
随便发挥9 小时前
Leetcode 剑指 Offer II 186. 文物朝代判断
leetcode
6Hzlia9 小时前
【Classic 150 刷题计划】 LeetCode 205. 同构字符串 | C++ 双向绑定与哈希表映射
c++·算法·leetcode
午彦琳1 天前
2026.9.17
数据结构·算法·leetcode
木井巳1 天前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
All for pursuit.1 天前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
圣保罗的大教堂1 天前
leetcode 1477. 找两个和为目标值且不重叠的子数组 中等
leetcode