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;

    }
}
相关推荐
We་ct19 分钟前
LeetCode 3. 无重复字符的最长子串:滑动窗口最优解演进与解析
前端·算法·leetcode·typescript
棱镜Coding33 分钟前
LeetCode-Hot100 31.K个一组反转链表
算法·leetcode·链表
v_for_van1 小时前
力扣刷题记录1(无算法背景,纯C语言)
算法·leetcode·职场和发展
踩坑记录2 小时前
leetcode hot100 25. K 个一组翻转链表 hard
leetcode·链表
客卿1232 小时前
力扣二叉树简单题整理(第二集)
算法·leetcode·职场和发展
爱编码的傅同学2 小时前
【今日算法】LeetCode 543.二叉树的直径 621.任务调度器 739.每日温度
数据结构·算法·leetcode
sin_hielo2 小时前
leetcode 3651
数据结构·算法·leetcode
Remember_9932 小时前
【LeetCode精选算法】位运算专题
java·开发语言·jvm·后端·算法·leetcode
源代码•宸2 小时前
Leetcode—102. 二叉树的层序遍历【中等】
经验分享·后端·算法·leetcode·职场和发展·golang·slice
好学且牛逼的马2 小时前
【Hot100|20-LeetCode 240. 搜索二维矩阵 II 】
linux·算法·leetcode