当前位置:网站首页>LeetCode_235_Last Common Ancestor of Binary Search Tree
LeetCode_235_Last Common Ancestor of Binary Search Tree
2022-07-30 11:37:00 【Fitz1318】
题目链接
题目描述
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先.
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先).”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]

示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6.
示例 2:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
输出: 2
解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身.
说明:
- 所有节点的值都是唯一的.
p、q为不同节点且均存在于给定的二叉搜索树中.
解题思路
二叉搜索树,Also known as binary search tree、二叉排序树.它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树.
- 如果两个节点值都小于根节点,说明他们都在根节点的左子树上,Continue to search on the left subtree
- 如果两个节点值都大于根节点,说明他们都在根节点的右子树上,Continue to search on the right subtree
- 如果一个节点值大于根节点,The other node value is less than the root node,It means that one of them is on the left subtree of the root node,One is on the right subtree of the root node,那么根节点就是他们的最近公共祖先节点
AC代码
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while ((root.val - p.val) * (root.val - q.val) > 0) {
//if on one side,Then the root node and p、q的差相乘是正数,继续往下找
root = p.val < root.val ? root.left : root.right;
}
//如果相乘的结果是负数,说明p和q位于根节点的两侧
//如果为0,Indicates that at least one of them is the root node
return root;
}
}
边栏推荐
- Assembly to implement bubble sort
- 还在用Swagger?我推荐这款零代码侵入的接口管理神器
- VLAN实验
- 面试官:Redis中的布隆过滤器与布谷鸟过滤器,你了解多少?
- 基于MySQL数据库,Redis缓存,MQ消息中间件,ES搜索引擎的高可用方案解析
- 电流继电器JL-8GB/11/AC220V
- Detailed explanation of @RequestBody and @ResponseBody
- MySQL——数据库基础
- Taobao/Tmall taobao comments q&a list interface API
- oracle 导出dmp文件类型为“故障转储文件”
猜你喜欢

360闷声干大事获赞无数,数字安全如何保障?还得看企业安全云

FPGA刷题——计数器(简易秒表、可置位计数器、加减计数器)

STM32F1 reads MLX90632 non-contact infrared temperature sensor

还在用Swagger?我推荐这款零代码侵入的接口管理神器

24. 两两交换链表中的节点

文本的对齐方式、行高、空间 等总结
![[ASP.NET Core] Dependency Injection for Option Classes](/img/3f/820b6e33897cf385c3206c02d741f8.png)
[ASP.NET Core] Dependency Injection for Option Classes

High energy output!Tencent's internal MyCat middleware manual, both theoretical and practical

EA中的业务对象和业务实体你分得清吗?

I built another wheel: GrpcGateway
随机推荐
"Learning Cloud Networking with Teacher Tang" - Problem Location - The host is working but the container is not working
编译Hudi
salesforce使用方法(salesforce authenticator下载)
TensorFlow自定义训练函数
decodeURIComponent()、eval()、encodeURIComponent()
Log4j有哪几种日志级别呢?
向上管理读书笔记
ESP32CAM 1838接收红外遥控器信号
The package of idea is not hollow
流水线上的农民:我在工厂种蔬菜
活动速递| Apache Doris 性能优化实战系列直播课程初公开,诚邀您来参加!
TensorFlow自定义训练函数
数据库性能系列之索引(上)
柔性机械系统分布参数建模及其控制的研究与进展
现在报PMP还来得及参加9月的考试吗?分享敏捷全真模拟题
Meituan internal push + school recruitment written test + summary of knowledge points
2022-07-29 顾宇佳 学习笔记 异常处理
Native js create table
EA中的业务对象和业务实体你分得清吗?
还在用Swagger?我推荐这款零代码侵入的接口管理神器