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;

    }
}
相关推荐
Logic1011 小时前
关于汉诺塔问题的分析
c语言·算法·递归·函数·解题思路·递归函数·汉诺塔问题
All for pursuit.3 小时前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
代码什么用5 小时前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.5 小时前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
yi0116 小时前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b6 小时前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
0+1111 天前
算法 --模拟
c++·算法·leetcode
Nil2081 天前
leetcode 739每日温度
算法·leetcode·职场和发展
xqqxqxxq1 天前
LeetCode Hot100 矩阵专题题解笔记
笔记·leetcode·矩阵
All for pursuit.1 天前
【贪心-4】581.最短无序连续子数组
数据结构·c++·算法·leetcode