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;

    }
}
相关推荐
We་ct24 分钟前
LeetCode 173. 二叉搜索树迭代器:BSTIterator类 实现与解析
前端·算法·leetcode·typescript
踩坑记录1 小时前
leetcode hot100 79. 单词搜索 medium 递归回溯
leetcode
Rhystt2 小时前
代码随想录第二十六天|669. 修剪二叉搜索树、108.将有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树
数据结构·c++·算法·leetcode
TracyCoder1234 小时前
LeetCode Hot100(57/100)——5. 最长回文子串
算法·leetcode·职场和发展
WZ188104638694 小时前
LeetCode第20题
算法·leetcode
吕司4 小时前
LeetCode Hot Code——三数之和
数据结构·算法·leetcode
YGGP4 小时前
【Golang】LeetCode 54. 螺旋矩阵
算法·leetcode·矩阵
TracyCoder1235 小时前
LeetCode Hot100(58/100)——138. 随机链表的复制
leetcode·链表
Frostnova丶5 小时前
LeetCode 868. 二进制间距
算法·leetcode
WZ188104638696 小时前
LeetCode第54题
算法·leetcode