当前位置:网站首页>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 != qp和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;
}
}
边栏推荐
- High energy output!Tencent's internal MyCat middleware manual, both theoretical and practical
- JSP 语法简介说明
- 分布式限流 redission RRateLimiter 的使用及原理
- Jingdong school recruited written test questions + summary of knowledge points
- 听到'演员工作比工人辛苦,吃得也不如工人好?'我笑了
- idea的package没有空心
- MySQL database maintenance
- Differences between lock spin and mutex usage scenarios
- 现在报PMP还来得及参加9月的考试吗?分享敏捷全真模拟题
- 【JZ64 求1+2+3+...+n】
猜你喜欢

Explain the problem of change exchange in simple terms - the shell of the backpack problem

VLAN实验

I built another wheel: GrpcGateway

Introduction to IoT Technologies: Chapter 6

STM32F1 reads MLX90632 non-contact infrared temperature sensor

RY-D1/1电压继电器

基于MySQL数据库,Redis缓存,MQ消息中间件,ES搜索引擎的高可用方案解析

Current relay JL-8GB/11/AC220V

数据库性能系列之索引(上)

stm32 RTC闹钟唤醒低功耗模式
随机推荐
@RequestBody 和 @ResponseBody 详解
电压继电器HDY-A/1-220VAC-1
横向对比5种常用的注册中心,无论是用于面试还是技术选型,都非常有帮助
电压继电器SRMUVS-100VAC-2H2D
Vim plugin GrepIt
久经沙场的程序员居然也被某鱼的假程序员骗了,程序员之间的信任应该是最高的,他一个人毁了这种信任感
简述controller,service,repository注解的用法(谈谈application.properties的作用)
柔性机械系统分布参数建模及其控制的研究与进展
基于.NetCore开发博客项目 StarBlog - (16) 一些新功能 (监控/统计/配置/初始化)
美团内推+校招笔试题+知识点总结
【梦想起航】
Typroa alternative tool marktext
【ASP.NET Core】选项类的依赖注入
基于声信道分析的电缆隧道人员定位技术
TensorFlow custom training function
Manage reading notes upward
Drools 规则引擎一文读懂
Redis 主从复制
Still using Swagger?I recommend this interface management artifact with zero code intrusion
ABP学习资源整理