当前位置:网站首页>剑指 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;
}
}
边栏推荐
- 华泰证券是国家认可的券商吗?开户安不安全?
- Naacl-22 | introduce the setting of migration learning on the prompt based text generation task
- 30余家机构联合发起数字藏品行业倡议,未来会如何前进?
- Prosperity is exhausted, things are right and people are wrong: where should personal webmasters go
- BigFilter全局交易防重组件的介绍与应用
- 9 - 类
- In Linux, I call odspcmd to query the database information. How to output silently is to only output values. Don't do this
- With this PDF, we finally got offers from eight major manufacturers, including Alibaba, bytek and Baidu
- 攻防世界 MISC 高手进阶区 001 normal_png
- Logo special training camp section II collocation relationship between words and graphics
猜你喜欢

攻防世界 misc 进阶区 2017_Dating_in_Singapore

攻防世界 MISC 進階區 Erik-Baleog-and-Olaf

都说软件测试很简单有手就行,但为何仍有这么多劝退的?

Attack and Defense World MISC Advanced Area Erik baleog and Olaf

新版判断PC和手机端代码,手机端跳转手机端,PC跳转PC端最新有效代码

BigFilter全局交易防重组件的介绍与应用

Mongodb aggregation operation summary

Why is Dameng data called the "first share" of domestic databases?

Lost in the lock world of MySQL

UML diagram memory skills
随机推荐
环境加密技术解析
md5工具类
Apachecn translation, proofreading, note sorting activity progress announcement 2022.7
Common shortcut keys for hbuilder x
模拟摇杆控制舵机
Prosperity is exhausted, things are right and people are wrong: where should personal webmasters go
Jvm-Sandbox-Repeater的部署
记录:关于Win10系统中Microsoft Edge上的网页如何滚动截屏?
Introducing QA into the software development lifecycle is the best practice that engineers should follow
高中物理:直线运动
蓝队攻防演练中的三段作战
面试必备 LeetCode 链表算法题汇总,全程干货!
Redis的持久化机制
Common open source codeless testing tools
阿里推出新品牌“瓴羊”,致力成为“数字化领头羊”
Li Kou 98: verify binary search tree
Mongodb aggregation operation summary
High school physics: linear motion
PostgreSQL JOIN实践及原理
Attack and defense world misc advanced area Hong