当前位置:网站首页>力扣 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)
边栏推荐
猜你喜欢

【Arduino】重生之Arduino 学僧(1)

2022.6.10 STM32MP157串口时钟的学习

Lightroom classic 2022 v11.4 Chinese version "latest resources"

PZK学C语言之数据类型,进制转换,输入输出,运算符,分支语句ifelse
![[MVC Architecture] MVC model](/img/71/e10da490d5f0098c64b33e77d158e7.png)
[MVC Architecture] MVC model

Day 3. Suicidal ideation and behavior in institutions of higher learning: A latent class analysis

Chrome 如何快速将一组正在浏览的网页(tabs)转移到另一台设备(电脑)上

AE 3D粒子系统插件:Trapcode Particular

Stm32-fsmc extended memory SRAM

Cesium教程 (1) 界面介绍-3dtiles加载-更改鼠标操作设置
随机推荐
Redis在windows下的idea连接不上问题
【11】二进制编码:“手持两把锟斤拷,口中疾呼烫烫烫”?
代码随想录笔记_哈希_242有效的字母异位词
力扣题解 单调栈
LaTeX中多个公式公用一个序号时
arcgis style样式表文件转换成geoserver sld文件
编程学习记录——第7课【函数】
【头歌】重生之我在py入门实训中(3): if条件语句
1 semi automatic crawler
[song] rebirth of me in py introductory training (12): Matplotlib interface and common graphics
人月神话阅读笔记
Baiwen driving Daquan learning (II) I2C driving
制作视频后期特效需要什么工具?
arcgis for js api-入门系列
A photo breaks through the face recognition system: you can nod your head and open your mouth, netizens
Dpdk network protocol stack VPP OVS DDoS Sdn nfv virtualization high performance expert Road
浅记一下十大排序
【头歌】重生之数据科学导论——回归进阶
[MySQL learning] 8
力扣题解 动态规划(3)