当前位置:网站首页>力扣 236. 二叉树的最近公共祖先
力扣 236. 二叉树的最近公共祖先
2022-07-27 05:21:00 【最后一只三脚兽】
递归实现
解题思路

当我们从根节点往下遍历时,对于遍历到的节点来说祖先节点只有两种情况:
- 一种是两个节点在同一边,此时祖先节点必然在它们都在的一边,如上图遍历在根节点时的B和H
- 第二种是两个节点分别在两边,此时该节点就是它们的祖先节点,直接返回,如上图遍历在根节点时的D和I
实现的思路
- 找节点p和q,如果找到了就返回,当某个节点左边找到了p和q之一,右边也找到了p和q之一,说明此时为第二种情况,该节点作为祖先节点直接返回即可。
- 如果发现某个节点左边找到了p或q,右边没找到,说明上传上来的这个节点就是祖先节点
代码
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null)return null;
if(root == p)return p;
if(root == q)return q;
TreeNode l = lowestCommonAncestor(root.left,p,q);
TreeNode r = lowestCommonAncestor(root.right,p,q);
if(l != null && r != null)return root;
if(l != null)return l;
else return r;
}
}
- 时间复杂度 O(n)
- 空间复杂度 O(n)
边栏推荐
- 安全帽反光衣检测识别数据集和yolov5模型
- Unittest套件与运行器
- 李宏毅 2020 深度学习与人类语言处理 DLHLP-Conditional Generation by RNN and Attention-p22
- 这是我的博客
- 韦东山 数码相框 项目学习(四)简易的TXT文档显示器(电纸书)
- [song] rebirth of me in py introductory training (8): module
- Speech and Language Processing (3rd ed. draft) Chapter 2 ——正则表达式,文本归一化,编辑距离 阅读笔记
- Super remote connection management tool: Royal TSX
- When multiple formulas in latex share a sequence number
- operator() 用法之一
猜你喜欢
随机推荐
[first song] rebirth of me in py introductory training (2): formula programming
C语言-文件操作
[first song] Introduction to data science of rebirth -- return to advanced level
acwing每日一题 正方形数组的数目
开源WebGIS-相关知识
What tools are needed to make video post effects?
[MVC Architecture] MVC model
Chrome 如何快速将一组正在浏览的网页(tabs)转移到另一台设备(电脑)上
C# Json编码在TCP通讯中的一些使用总结
malloc和new之间的不同-实战篇
面试常问Future、FutureTask和CompletableFuture
geonode geoserver win10 安装教程(亲测)
STM32-FSMC外扩内存SRAM
socket编程二:使用select
STM32-红外遥控
C language - linear sequence table
Xmind 思维导图 2022 v12.0.3中文版更新了哪些内容?
基于C#的Winform对Access数据库进行操作(mdb结尾)
【头歌】重生之机器学习-线性回归
【12】理解电路:从电报机到门电路,我们如何做到“千里传信”?








