当前位置:网站首页>Leetcode 235. 二叉搜索树的最近公共祖先
Leetcode 235. 二叉搜索树的最近公共祖先
2022-08-09 22:05:00 【LuZhouShiLi】
Leetcode 235. 二叉搜索树的最近公共祖先
题目
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
思路
- 确定递归函数返回值以及参数:参数就是当前节点,以及两个节点p,q
- 终止条件,遇到空值 直接返回即可
- 遍历二叉搜索树的时候就是寻找区间[p->val,q->val] 如果p->val > cur->val, 同时q->val > cur->val,那么遍历右子树,反之遍历左子树。
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
public:
TreeNode* traversal(TreeNode* cur,TreeNode *p,TreeNode *q)
{
if(cur == NULL)
{
return cur;
}
if(cur->val > p->val && cur->val > q->val)
{
// 递归左子树
TreeNode* left = traversal(cur->left,p,q);
if(left != NULL)
{
return left;
}
}
if(cur->val < p->val && cur->val < q->val)
{
// 递归右子树
TreeNode* right = traversal(cur->right,p,q);
if(right != NULL)
{
return right;
}
}
return cur;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return traversal(root,p,q);
}
};
边栏推荐
猜你喜欢
How do task flow executors work?
One Pass 2074: [21CSPJ Popularization Group] Candy
Activiti7审批流
深度学习100例 —— 循环神经网络(RNN)实现股票预测
Transfer Learning & Kemin Initialization
Qt message mechanism and events
OSG笔记:使用setFontResolution设置字体分辨率
p5.js实现的炫酷星体旋转动画
EasyExcel使用
leetcode brush questions diary Calculate the number of elements on the right that is less than the current element
随机推荐
如何坚持使用程序化系统?
R语言ggplot2可视化:使用ggpubr包的ggerrorplot函数可视化误差线(可视化不同水平均值点以及se标准误差)、设置add参数为dotplot添加点阵图
daemon
Linux 配置MySQL
A1. Prefix Flip (Easy Version)
Analyze the Add() method in Fragment management from the source code
OFDM 十六讲 7 - Inter-Symbol-Interference
【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
shell数组
OKR 锦囊妙计
[WeChat applet development (8)] Summary of audio background music playback problems
2022年中国第三方证券APP创新专题分析
都在说云原生,那云原生到底是什么?
【Leetcode】2104. Sum of Subarray Ranges
Socket发送缓冲区接收缓冲区快问快答
18-GuliMall 压力测试与性能监控
量化交易接口系统有哪些稳定性?
c:forEach varStatus属性
What kind of mentality do you need to have when using the stock quantitative trading interface
深度学习100例 —— 循环神经网络(RNN)实现股票预测