当前位置:网站首页>LeetCode_236_二叉树的最近公共祖先
LeetCode_236_二叉树的最近公共祖先
2022-07-30 11:15: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
均存在于给定的二叉树中。
解题思路
- 从两个节点往上找,每个节点都往上走,直到走到根节点。
- 那么根节点到这两个节点的连线肯定有相交的地方
- 如果是从上往下走,那么最后一次相交的节点就是他们的最近公共祖先
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) {
//记录下p和它的祖先节点,从p节点开始一直到根节点
ancestors.add(p);
p = parent.get(p);
}
while (!ancestors.contains(q)) {
//查看p和它的祖先节点是否包含q
//如果不包含,再看是否包含q的父节点
q = parent.get(q);
}
return q;
}
}
边栏推荐
猜你喜欢
【ASP.NET Core】选项类的依赖注入
API 网关 APISIX 在Google Cloud T2A 和 T2D 的性能测试
HJY-F931A/YJ三相电压继电器
Performance testing of API Gateway APISIX on Google Cloud T2A and T2D
程序环境和预处理(详解)
The configuration process and related syntax of writing markdown format notes in vscode
TestNg整合Retry代码
物联网技术概论:第6章
类和对象—6个默认成员函数
Typroa alternative tool marktext
随机推荐
Performance testing of API Gateway APISIX on Google Cloud T2A and T2D
Telerik2022 R2,有效的自动化测试
明德扬FPGA开发板XILINX-K7核心板Kintex7 XC7K325 410T工业级
向上管理读书笔记
"Learning Cloud Networking with Teacher Tang" - Problem Location - The host is working but the container is not working
真正懂经营管理的CIO具备哪些特质
优酷VIP会员周卡只需7.5元,看《沉香如屑》用优酷视频
STM32F1 reads MLX90632 non-contact infrared temperature sensor
【数据库基础】redis使用总结
WEB3之路(一)-- solidity学习笔记
SQL language and paging rownum analysis in Oracle
Beyond Stream Processing !第四届实时计算 Flink 挑战赛启动,49 万奖金等你来拿!
The package of idea is not hollow
简述controller,service,repository注解的用法(谈谈application.properties的作用)
FPGA刷题——计数器(简易秒表、可置位计数器、加减计数器)
HJY-F931A/YJ three-phase voltage relay
Database transactions, JDBC operations and data types
MySQL database maintenance
三个点语法和DOM观察者
360 released a future-oriented EDR to protect the security of government and enterprise user terminals in an all-round way