当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
随机推荐
Classes and Objects - 6 Default Member Functions
VSCode更改插件的安装位置
单片机开发之静态LED显示
pg_rewind 修复主备环境的时间线
不用if分支对同一个变量做判断的方法
[ASP.NET Core] Dependency Injection for Option Classes
流水线上的农民:我在工厂种蔬菜
又爆神作!阿里爆款MySQL高级宝典开源,直抵P7
Vim plugin GrepIt
Beyond Stream Processing !第四届实时计算 Flink 挑战赛启动,49 万奖金等你来拿!
HJY-F931A/YJ三相电压继电器
电压继电器HDY-A/1-220VAC-1
Native js create table
[Cloud-Building Co-creation] Huawei Cloud and Hongmeng collaborate to cultivate innovative developers
模糊离散事件系统的可测性
正则表达式快速入门笔记
LCD1602 display experiment developed by single chip microcomputer
RY-D1/1 Voltage Relay
decodeURIComponent()、eval()、encodeURIComponent()
RY-D1/1电压继电器








