当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
随机推荐
decodeURIComponent()、eval()、encodeURIComponent()
久经沙场的程序员居然也被某鱼的假程序员骗了,程序员之间的信任应该是最高的,他一个人毁了这种信任感
Kubernetes 入门实战03 中级篇
电流继电器JL-8GB/11/AC220V
oracle export dmp file type as "crash dump file"
Typroa alternative tool marktext
unity3d C#语言基础(继承)
STM32F1 reads MLX90632 non-contact infrared temperature sensor
eric6教程(电脑的配置基本知识)
mysql与redis 区别
ABP学习资源整理
数据库事务,JDBC操作和数据类型
Native js create table
PanGu-Coder: 函数级的代码生成模型
Typroa 替代工具marktext
三个点语法和DOM观察者
Drools 规则引擎一文读懂
Beyond Stream Processing !第四届实时计算 Flink 挑战赛启动,49 万奖金等你来拿!
ODrive应用 #4 配置参数&指令「建议收藏」
基于.NetCore开发博客项目 StarBlog - (16) 一些新功能 (监控/统计/配置/初始化)









