当前位置:网站首页>剑指 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;
}
}
边栏推荐
- 2022-07-04: what is the output of the following go language code? A:true; B:false; C: Compilation error. package main import “fmt“ func main() { fmt.Pri
- 华泰证券是国家认可的券商吗?开户安不安全?
- Flask 上下文详解
- MYSQL架构——用户权限与管理
- 特征缩放 标准化 归一化
- The proofreading activity of data science on the command line second edition was restarted
- 攻防世界 MISC 进阶区 3-11
- Summary of index operations in mongodb
- php短视频源码,点赞时会有大拇指动画飘起
- Easy to use app recommendation: scan QR code, scan barcode and view history
猜你喜欢
Domestic database chaos
国产数据库乱象
The Sandbox 和数字好莱坞达成合作,通过人力资源开发加速创作者经济的发展
2022-07-04:以下go语言代码输出什么?A:true;B:false;C:编译错误。 package main import “fmt“ func main() { fmt.Pri
攻防世界 MISC 进阶 glance-50
More than 30 institutions jointly launched the digital collection industry initiative. How will it move forward in the future?
NFT Insider #64:电商巨头eBay提交NFT相关商标申请,毕马威将在Web3和元宇宙中投入3000万美元
Concurrent optimization summary
30余家机构联合发起数字藏品行业倡议,未来会如何前进?
嵌入式开发:技巧和窍门——提高嵌入式软件代码质量的7个技巧
随机推荐
Domestic database chaos
攻防世界 MISC 进阶区 Ditf
Gnawing down the big bone - sorting (II)
制作条形码的手机App推荐
面试必备 LeetCode 链表算法题汇总,全程干货!
Detailed explanation of heap sort code
Logo special training camp section 1 Identification logo and logo design ideas
Logo special training camp Section V font structure and common design techniques
POM in idea XML dependency cannot be imported
新版判断PC和手机端代码,手机端跳转手机端,PC跳转PC端最新有效代码
Challenges faced by virtual human industry
The proofreading activity of data science on the command line second edition was restarted
Apachecn translation, proofreading, note sorting activity progress announcement 2022.7
LOGO特训营 第五节 字体结构与设计常用技法
Embedded development: skills and tricks -- seven skills to improve the quality of embedded software code
Li Kou 98: verify binary search tree
Common open source codeless testing tools
[acwing] solution of the 58th weekly match
It is said that software testing is very simple, but why are there so many dissuasions?
攻防世界 MISC 进阶区 Erik-Baleog-and-Olaf