当前位置:网站首页>剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
2022-07-04 22:20:00 【LuZhouShiLi】
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
题目
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
思路
- 当p,q都在root的右子树中,则遍历root.right
- 当p,q都在root的左子树,则遍历root.left
- 当p,q在root两边,说明找到了最近公共祖先
代码
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(root != null)
{
if(root.val < p.val && root.val < q.val)
{
// 字节点都比root值要小 说明pq在左子树 遍历左子树
root = root.right;
}
else if(root.val > p.val && root.val > q.val)
{
root = root.left;
}
else{
break;// p q在root左右两侧 说明root就是最近公共祖先 直接跳出
}
}
return root;
}
}
边栏推荐
- md5工具类
- LOGO特训营 第五节 字体结构与设计常用技法
- 攻防世界 misc 进阶区 2017_Dating_in_Singapore
- leetcode 72. Edit Distance 编辑距离(中等)
- Redis sentinel simply looks at the trade-offs between distributed high availability and consistency
- Locust performance test - environment construction and use
- Postgresqlql advanced skills pivot table
- The sandbox has reached a cooperation with digital Hollywood to accelerate the economic development of creators through human resource development
- High school physics: linear motion
- LOGO特訓營 第三節 首字母創意手法
猜你喜欢
30余家机构联合发起数字藏品行业倡议,未来会如何前进?
PMO: compare the sample efficiency of 25 molecular optimization methods
Logo special training camp Section V font structure and common design techniques
Tla+ introductory tutorial (1): introduction to formal methods
【OpenGL】笔记二十九、抗锯齿(MSAA)
How to send a reliable request before closing the page
UML图记忆技巧
NFT insider 64: e-commerce giant eBay submitted an NFT related trademark application, and KPMG will invest $30million in Web3 and metauniverse
安装人大金仓数据库
Hit the core in the advanced area of misc in the attack and defense world
随机推荐
idea中pom.xml依赖无法导入
好用app推荐:扫描二维码、扫描条形码并查看历史
NFT Insider #64:电商巨头eBay提交NFT相关商标申请,毕马威将在Web3和元宇宙中投入3000万美元
SPSS installation and activation tutorial (including network disk link)
高中物理:直线运动
Tiktok actual combat ~ the number of comments is updated synchronously
Alibaba launched a new brand "Lingyang" and is committed to becoming a "digital leader"
LOGO特训营 第四节 字体设计的重要性
记录:关于Win10系统中Microsoft Edge上的网页如何滚动截屏?
How diff are the contents of the same configuration item in different environments?
How to reset the password of MySQL root account
How to transfer to software testing, one of the high paying jobs in the Internet? (software testing learning roadmap attached)
9 - 类
Domestic database chaos
Unity-VScode-Emmylua配置报错解决
leetcode 72. Edit Distance 编辑距离(中等)
不同环境相同配置项的内容如何diff差异?
It is said that software testing is very simple, but why are there so many dissuasions?
【OpenGL】笔记二十九、抗锯齿(MSAA)
PostgreSQL JOIN实践及原理