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;

    }
}
相关推荐
文丑颜不良啊1 小时前
LeetCode2841~2860题目解析
java·leetcode
文丑颜不良啊3 小时前
LeetCode2921~2940题目解析
java·leetcode
文丑颜不良啊5 小时前
LeetCode2901~2920题目解析
java·leetcode
文丑颜不良啊7 小时前
LeetCode2861~2880题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2821~2840题目解析
java·leetcode
Pniubi1 天前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表
文丑颜不良啊1 天前
LeetCode2741~2760题目解析
java·leetcode
俊俊几年的1 天前
动态规划(Dynamic Programming)详解:从入门到 LeetCode Hot 100
linux·c++·算法·leetcode·嵌入式·动态规划·c
希望我万事顺遂2 天前
力扣hot100-滑动窗口最大值
数据结构·算法·leetcode
是main不是漫2 天前
【双指针|LeetCode1089 复写零】巧用逆向思路,破解原地覆盖陷阱
数据结构·算法·leetcode