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;

    }
}
相关推荐
py有趣1 小时前
力扣热门100题之接雨水
算法·leetcode
py有趣5 小时前
力扣热门100题之合并区间
算法·leetcode
派大星~课堂5 小时前
【力扣-138. 随机链表的复制 ✨】Python笔记
python·leetcode·链表
py有趣5 小时前
力扣热门100题之最小覆盖子串
算法·leetcode
北顾笙9806 小时前
day15-数据结构力扣
数据结构·算法·leetcode
人道领域6 小时前
【LeetCode刷题日记:24】两两交换链表
算法·leetcode·链表
北顾笙9806 小时前
day16-数据结构力扣
数据结构·算法·leetcode
wsoz7 小时前
Leetcode子串-day4
c++·算法·leetcode
会编程的土豆7 小时前
【数据结构与算法】二叉树大总结
数据结构·算法·leetcode
y = xⁿ7 小时前
【LeetCode Hot100】动态规划:T70:爬楼梯 T118:杨辉三角形 T198:打家劫舍
算法·leetcode·动态规划