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;

    }
}
相关推荐
薰衣草23331 小时前
一天两道力扣(1)
算法·leetcode·职场和发展
爱coding的橙子2 小时前
每日算法刷题Day41 6.28:leetcode前缀和2道题,用时1h20min(要加快)
算法·leetcode·职场和发展
前端拿破轮5 小时前
不是吧不是吧,leetcode第一题我就做不出来?😭😭😭
后端·算法·leetcode
前端拿破轮5 小时前
😭😭😭看到这个快乐数10s,我就知道快乐不属于我了🤪
算法·leetcode·typescript
今天背单词了吗98010 小时前
算法学习笔记:4.KMP 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·考研·算法·leetcode·kmp算法
hn小菜鸡16 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
亮亮爱刷题10 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
zmuy10 天前
124. 二叉树中的最大路径和
数据结构·算法·leetcode
chao_78910 天前
滑动窗口题解——找到字符串中所有字母异位词【LeetCode】
数据结构·算法·leetcode
Alfred king10 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法