当前位置:网站首页>剑指 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;
}
}
边栏推荐
- Interview essential leetcode linked list algorithm question summary, whole process dry goods!
- Challenges faced by virtual human industry
- Detailed explanation of flask context
- 攻防世界 MISC 高手进阶区 001 normal_png
- 啃下大骨头——排序(二)
- 攻防世界 MISC 进阶 glance-50
- Force buckle_ Palindrome number
- 高中物理:直线运动
- Li Kou 98: verify binary search tree
- 【OpenGL】笔记二十九、抗锯齿(MSAA)
猜你喜欢

质量体系建设之路的分分合合

NFT Insider #64:电商巨头eBay提交NFT相关商标申请,毕马威将在Web3和元宇宙中投入3000万美元

Erik baleog and Olaf, advanced area of misc in the attack and defense world

Logo special training camp Section IV importance of font design

UML diagram memory skills

Redis的持久化机制

Introduction and application of bigfilter global transaction anti duplication component

Tla+ introductory tutorial (1): introduction to formal methods

安装人大金仓数据库

NFT insider 64: e-commerce giant eBay submitted an NFT related trademark application, and KPMG will invest $30million in Web3 and metauniverse
随机推荐
[cooking record] - stir fried 1000 pieces of green pepper
[Yugong series] go teaching course 003-ide installation and basic use in July 2022
How to manage 15million employees easily?
Attack and defense world misc advanced grace-50
PostgreSQL服务端编程聚合和分组
【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用
Interview essential leetcode linked list algorithm question summary, whole process dry goods!
Flask 上下文详解
Common shortcut keys for hbuilder x
Taobao commodity review API interface (item_review get Taobao commodity review API interface), tmall commodity review API interface
MySQL storage data encryption
将QA引入软件开发生命周期是工程师要遵循的最佳实践
阿里推出新品牌“瓴羊”,致力成为“数字化领头羊”
记录:关于Win10系统中Microsoft Edge上的网页如何滚动截屏?
Google Earth Engine(GEE)——以MODIS/006/MCD19A2为例批量下载逐天AOD数据逐天的均值、最大值、最小值、标准差、方差统计分析和CSV下载(北京市各区为例)
面试必备 LeetCode 链表算法题汇总,全程干货!
md5工具类
Detailed explanation of flask context
The new version judges the code of PC and mobile terminal, the mobile terminal jumps to the mobile terminal, and the PC jumps to the latest valid code of PC terminal
Erik baleog and Olaf, advanced area of misc in the attack and defense world