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;

    }
}
相关推荐
TracyCoder12328 分钟前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
weixin_445476684 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王4 小时前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展
Swift社区4 小时前
LeetCode 385 迷你语法分析器
算法·leetcode·职场和发展
期末考复习中,蓝桥杯都没时间学了5 小时前
力扣刷题10
算法·leetcode·职场和发展
爱跑步的程序员~7 小时前
LeetCode 24. 两两交换链表中的节点
算法·leetcode·链表
芒克芒克8 小时前
LeetCode 实现 strStr() 题解(暴力匹配法)
算法·leetcode·职场和发展
历程里程碑8 小时前
双指针 --- 接雨水
java·数据结构·python·算法·leetcode·职场和发展·tornado
Anastasiozzzz10 小时前
LeetCode Hot100 739.dailyTemperatures 每日温度
算法·leetcode·职场和发展
卷卷的小趴菜学编程10 小时前
算法篇----递归回溯
c++·算法·递归·回溯算法·暴力搜索·floodfill算法·二叉树深搜