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;

    }
}
相关推荐
liuyao_xianhui1 天前
优选算法_栈_删除字符中的所有相邻重复项_C++
开发语言·数据结构·c++·python·算法·leetcode·链表
老虎06271 天前
LeetCode热题100 刷题笔记(第三天)链表 「两数相加」
笔记·leetcode·链表
会编程的土豆1 天前
【leetcode hot 100】二叉树
算法·leetcode
Mr_Xuhhh1 天前
LeetCode 热题 100 刷题笔记:数组与排列的经典解法(续)
算法·leetcode·职场和发展
Mr_Xuhhh1 天前
LeetCode 热题 100 刷题笔记:高频面试题详解(215 & 347)
算法·leetcode·排序算法
童话ing1 天前
【LeetCode】239.滑动窗口最大值
数据结构·算法·leetcode·golang
_日拱一卒1 天前
LeetCode:和为K的子数组
算法·leetcode·职场和发展
Mr_Xuhhh1 天前
LeetCode 热题 100 刷题笔记:数组与排列的经典解法
数据结构·算法·leetcode
老四啊laosi1 天前
[双指针] 3. 力扣--快乐数
算法·leetcode·快慢指针
会编程的土豆1 天前
leetcode hot 100 之哈希
算法·leetcode·哈希算法