当前位置:网站首页>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;
}
}
边栏推荐
- 基于多目标两阶段随机规划方法的电热联合系统调度
- [Database basics] redis usage summary
- UE5 GAS 学习笔记 后记0
- STM32F1读取MLX90632非接触式红外温度传感器
- I built another wheel: GrpcGateway
- 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
- 听到'演员工作比工人辛苦,吃得也不如工人好?'我笑了
- Performance testing of API Gateway APISIX on Google Cloud T2A and T2D
- 程序环境和预处理(详解)
- FPGA刷题——计数器(简易秒表、可置位计数器、加减计数器)
猜你喜欢
随机推荐
LCD1602 display experiment developed by single chip microcomputer
MySQL——数据库基础
听到'演员工作比工人辛苦,吃得也不如工人好?'我笑了
Hu-cang integrated e-commerce project (1): project background and structure introduction
salesforce使用方法(salesforce authenticator下载)
重写并自定义依赖的原生的Bean方法
柔性机械系统分布参数建模及其控制的研究与进展
Database transactions, JDBC operations and data types
unity3d C#语言基础(继承)
Typroa alternative tool marktext
decodeURIComponent(), eval(), encodeURIComponent()
Explain the problem of change exchange in simple terms - the shell of the backpack problem
PanGu-Coder: 函数级的代码生成模型
Manage reading notes upward
原生js 创建表格
京东校招笔试题+知识点总结
正则表达式快速入门笔记
Vim plugin GrepIt
Log4j additivity属性简介说明
Differences between lock spin and mutex usage scenarios









