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;

    }
}
相关推荐
smj2302_7968265214 小时前
解决leetcode第3985题回文数组求和
数据结构·python·算法·leetcode
旖-旎18 小时前
《LeetCode 53 最大子数组和 || LeetCode 918 环形子数组的最大和》
c++·算法·leetcode·动态规划
海石20 小时前
单调栈复健,顺便,牺牲一下吧,空间复杂度!一切献给AC
算法·leetcode
海石20 小时前
JS击败94%,Hard题想不到动态规划,那就用数组和栈试试
算法·leetcode
伟大的车尔尼1 天前
回溯题目:N 皇后
回溯
alphaTao1 天前
LeetCode 每日一题 2026/7/6-2026/7/12
算法·leetcode
想吃火锅10051 天前
【leetcode】56.合并区间js
算法·leetcode·职场和发展
wabs6661 天前
关于动态规划【力扣72.编辑距离的思考】
算法·leetcode·动态规划
凌波粒1 天前
LeetCode--47.全排列 II(回溯算法)
算法·leetcode·职场和发展
凌波粒1 天前
LeetCode--53. 最大子序和(贪心算法)
算法·leetcode·贪心算法