当前位置:网站首页>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 != qp和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;
}
}
边栏推荐
猜你喜欢
随机推荐
干货|语义网、Web3.0、Web3、元宇宙这些概念还傻傻分不清楚?(中)
Drools 规则引擎一文读懂
Drag and drop events, dataTransfer, getBoundingClientRect
Detailed explanation of @RequestBody and @ResponseBody
Database dirty reads, non-repeatable reads, phantom reads and corresponding isolation levels
The battle-hardened programmer was also deceived by a fake programmer from a certain fish. The trust between programmers should be the highest, and he alone destroyed this sense of trust
VSCode更改插件的安装位置
Telerik2022 R2,有效的自动化测试
MySQL database maintenance
Taobao/Tmall taobao comments q&a list interface API
XYplorer 23多语言,最好的管理软件之一
TensorFlow custom training function
电流继电器JL-8GB/11/AC220V
神经网络学习笔记3——LSTM长短期记忆网络
Transfer Learning技术研修
TestNg整合Retry代码
RandLA-Net复现记录
鸿湖万联扬帆富设备开发板正式合入OpenHarmony主干
UE5 GAS Study Notes Postscript 0
xshell使用技巧(赚分享平台怎么样)









