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;

    }
}
相关推荐
文丑颜不良啊10 小时前
LeetCode1461~1480题目解析
java·leetcode
Pniubi19 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
Patrick在香港1 天前
一个斜杠,把毫秒变成十几秒
android·数据库·python·性能优化·正则表达式·回溯·redos
旖旎夜光1 天前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
文丑颜不良啊1 天前
LeetCode1401~1420题目解析
java·leetcode
Nuanyt1 天前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表
文丑颜不良啊1 天前
LeetCode1341~1360题目解析
java·leetcode
海绵宝宝转agent1 天前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
Pniubi1 天前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展
j7~2 天前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归