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;

    }
}
相关推荐
洛水水8 小时前
【力扣100题】30.二叉树的直径
算法·leetcode·职场和发展
洛水水11 小时前
【力扣100题】32.将有序数组转换为二叉搜索树
数据结构·算法·leetcode
如竟没有火炬11 小时前
用队列实现栈
开发语言·数据结构·python·算法·leetcode·深度优先
水木流年追梦12 小时前
大模型入门-应用篇3-Agent智能体
开发语言·python·算法·leetcode·正则表达式
洛水水13 小时前
【力扣100题】31.二叉树的层序遍历
算法·leetcode·职场和发展
洛水水13 小时前
【力扣100题】41.爬楼梯
算法·leetcode·职场和发展
Pkmer13 小时前
LeetCode 上极少见的工程级滑窗实现
python·leetcode
sheeta199814 小时前
LeetCode 每日一题笔记 日期:2026.05.13 题目:1674. 使数组互补的最少操作次数
笔记·算法·leetcode
每天回答3个问题14 小时前
LeetCodeHot100|回溯算法、46.全排列、78.子集、17.电话号码的字母组合
算法·深度优先·回溯
YL2004042614 小时前
038翻转二叉树
数据结构·leetcode