当前位置:网站首页>二叉树专题--AcWing 19. 二叉树的下一个节点(找树中节点的后继)
二叉树专题--AcWing 19. 二叉树的下一个节点(找树中节点的后继)
2022-07-02 07:21:00 【Morgannr】
题意:
求二叉树中给定节点的后继。
时间复杂度:
(模拟) O(h)
思路:
分情况讨论即可,如下图所示:
- 如果当前节点有右儿子,则右子树中最左侧的节点就是当前节点的后继。比如F的后继是H;
- 如果当前节点没有右儿子,则需要沿着father域一直向上找,找到第一个是其father左儿子的节点,该节点的father就是当前节点的后继。比如当前节点是D,则第一个满足是其father左儿子的节点是C,则C的father就是D的后继,即F是D的后继。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode *father;
* TreeNode(int x) : val(x), left(NULL), right(NULL), father(NULL) {}
* };
*/
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* p) {
if (p->right)
{
p = p->right;
while (p->left)
{
p = p->left;
}
return p;
}
while (p->father && p == p->father->right) p = p->father;
return p->father;
}
};
边栏推荐
- 【AGC】构建服务3-认证服务示例
- Filtering of PCL
- PCL Eigen介绍及简单使用
- 14. Code implementation of semaphore
- [TS] 1368 seconds understand typescript generic tool types!
- (五)APA场景搭建之挡位控制设置
- HDU1228 A + B(map映射)
- How to get the password of cpolar?
- [SUCTF2018]followme
- The nanny level tutorial of flutter environment configuration makes the doctor green to the end
猜你喜欢
Introduction to MySQL 8 DBA foundation tutorial
Open the encrypted SQLite method with sqlcipher
618再次霸榜的秘密何在?耐克最新财报给出答案
4.随机变量
全网显示 IP 归属地,是怎么实现的?
Flink submitter
软件产品管理系统有哪些?12个最佳产品管理工具盘点
JSP webshell免杀——JSP的基础
618 what is the secret of dominating the list again? Nike's latest financial report gives the answer
华为AppLinking中统一链接的创建和使用
随机推荐
Nodejs+express+mysql simple blog building
JS settimeout() and interview questions
P1055 [NOIP2008 普及组] ISBN 号码
点云投影图片
华为游戏初始化init失败,返回错误码907135000
HDU1234 开门人和关门人(水题)
How to get the password of cpolar?
Oracle 笔记
JSP webshell free -- the basis of JSP
【快应用】text组件里的文字很多,旁边的div样式会被拉伸如何解决
互联网快讯:腾讯会议应用市场正式上线;Soul赴港递交上市申请书
Easyexcel, a concise, fast and memory saving excel processing tool
PCL 从一个点云中提取一个子集
Win11 arm系统配置.net core环境变量
华为应用市场应用统计数据问题大揭秘
UWA report uses tips. Did you get it? (the fourth bullet)
14.信号量的代码实现
SPSS做Shapiro-Wilk正态分析
Lunix reallocates root and home space memory
【ARK UI】HarmonyOS ETS的启动页的实现