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;

    }
}
相关推荐
alphaTao5 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1235 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi6 小时前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z21 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil20821 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2081 天前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil2081 天前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
局部有解1 天前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
Nil2081 天前
leetcode 75颜色分类
数据结构·算法·leetcode
aqiu1111111 天前
CodeTop按顺序刷题0003:LeetCode 206. 反转链表(迭代法图文详解与动态演示)
算法·leetcode·链表