当前位置:网站首页>LeetCode_236_Last Common Ancestor of a Binary Tree
LeetCode_236_Last Common Ancestor of a Binary Tree
2022-07-30 11:37:00 【Fitz1318】
题目链接
题目描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先.
百度百科中最近公共祖先的定义为:“对于有根树 T
的两个节点 p
、q
,最近公共祖先表示为一个节点 x
,满足 x
是 p
、q
的祖先且 x
的深度尽可能大(一个节点也可以是它自己的祖先).”
示例 1:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3 .
示例 2:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出:5
解释:节点 5 和节点 4 的最近公共祖先是节点 5 .因为根据定义最近公共祖先节点可以为节点本身.
示例 3:
输入:root = [1,2], p = 1, q = 2
输出:1
提示:
- 树中节点数目在范围
[2, 10^5]
内. -10^9 <= Node.val <= 10^9
- 所有
Node.val
互不相同 . p != q
p
和q
均存在于给定的二叉树中.
解题思路
- Look up from two nodes,每个节点都往上走,直到走到根节点.
- 那么根节点到这两个节点的连线肯定有相交的地方
- 如果是从上往下走,Then the last intersected nodes are their nearest common ancestors
AC代码
HashMap<TreeNode, TreeNode> parent = new HashMap<>();
Deque<TreeNode> queue = new LinkedList<>();
parent.put(root, null);
queue.offer(root);
while (!parent.containsKey(p) || !parent.containsKey(q)) {
//直到两个节点都找到为止
TreeNode tmp = queue.poll();
if (tmp.left != null) {
parent.put(tmp.left, tmp);
queue.offer(tmp.left);
}
if (tmp.right != null) {
parent.put(tmp.right, tmp);
queue.offer(tmp.right);
}
}
HashSet<TreeNode> ancestors = new HashSet<>();
while (p != null) {
//记录下pand its ancestor nodes,从p节点开始一直到根节点
ancestors.add(p);
p = parent.get(p);
}
while (!ancestors.contains(q)) {
//查看pand whether its ancestor node containsq
//如果不包含,再看是否包含q的父节点
q = parent.get(q);
}
return q;
}
}
边栏推荐
猜你喜欢
零代码开发入门:快速上手DIY函数公式的5个步骤
高能产出!腾讯内部的MyCat中间件手册,理论实操齐下
Explain the problem of change exchange in simple terms - the shell of the backpack problem
VSCode更改插件的安装位置
ESP32CAM 1838接收红外遥控器信号
STM32F1读取MLX90632非接触式红外温度传感器
async.js入门
Voltage relay h2d SRMUVS - 100 vac - 2
久经沙场的程序员居然也被某鱼的假程序员骗了,程序员之间的信任应该是最高的,他一个人毁了这种信任感
文本的对齐方式、行高、空间 等总结
随机推荐
基于.NetCore开发博客项目 StarBlog - (16) 一些新功能 (监控/统计/配置/初始化)
单片机开发之LCD1602显示实验
程序环境和预处理(详解)
Taobao/Tmall taobao comments q&a list interface API
AB测试 总结归纳
log4j中appender的简介说明
MySQL——数据库基础
基于空间特征选择的水下目标检测方法
UE5 GAS Study Notes Postscript 0
oracle 导出dmp文件类型为“故障转储文件”
Beyond Stream Processing!The 4th real-time computing Flink challenge is launched, and 490,000 prizes are waiting for you!
高手云集、丰富活动,斩获佳绩,超过2万名开发者参与的AI社团邀你加入!
【梦想起航】
听到'演员工作比工人辛苦,吃得也不如工人好?'我笑了
FPGA刷题——计数器(简易秒表、可置位计数器、加减计数器)
明德扬FPGA开发板XILINX-K7核心板Kintex7 XC7K325 410T工业级
优酷VIP会员周卡只需7.5元,看《沉香如屑》用优酷视频
AIX shell获取前几个月时间
C language - bitwise operations
Log4j additivity属性简介说明