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;

    }
}
相关推荐
剪一朵云爱着32 分钟前
力扣410. 分割数组的最大值
算法·leetcode
Swift社区33 分钟前
LeetCode 410 - 分割数组的最大值
算法·leetcode·职场和发展
ゞ 正在缓冲99%…34 分钟前
leetcode375.猜数字大小II
数据结构·算法·leetcode·动态规划
Emilia486.15 小时前
【Leetcode&nowcode】代码强化练习(二叉树)
算法·leetcode·职场和发展
墨染点香15 小时前
LeetCode 刷题【135. 分发糖果】
算法·leetcode·职场和发展
im_AMBER16 小时前
Leetcode 41
笔记·学习·算法·leetcode
Excuse_lighttime17 小时前
排序数组(快速排序算法)
java·数据结构·算法·leetcode·eclipse·排序算法
前进的李工18 小时前
LeetCode hot100:560 和为k的子数组:快速统计法
python·算法·leetcode·前缀和·哈希表
在等晚安么19 小时前
力扣面试经典150题打卡
java·数据结构·算法·leetcode·面试·贪心算法
py有趣20 小时前
LeetCode算法学习之移动0
学习·算法·leetcode