当前位置:网站首页>二叉树专题--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;
}
};
边栏推荐
- MySQL lethal serial question 3 -- are you familiar with MySQL locks?
- Analysis of hot spots in AI technology industry
- MYSQL环境配置
- Lunix reallocates root and home space memory
- UVM learning - object attribute of UVM phase
- MySQL数据库远程访问权限设置
- Easyexcel, a concise, fast and memory saving excel processing tool
- 02-taildir source
- 拆解美图SaaS:开着飞机换引擎
- 6种单例模式的实现方式
猜你喜欢

axis设备的rtsp setup头中的url不能带参

Overview of integrated learning

MySQL environment configuration

VSCode工具使用

Is this code PHP MySQL redundant?

【TS】1368- 秒懂 TypeScript 泛型工具类型!

使用华为性能管理服务,按需配置采样率

Internet News: Tencent conference application market was officially launched; Soul went to Hong Kong to submit the listing application

简洁、快速、节约内存的Excel处理工具EasyExcel

MongoDB 学习整理(条件操作符,$type 操作符,limit()方法,skip() 方法 和 sort() 方法)
随机推荐
Sus system availability scale
[TS] 1368 seconds understand typescript generic tool types!
UVM learning - build a simple UVM verification platform
华为快应用中如何实现同时传递事件对象和自定义参数
【AppLinking实战案例】通过AppLinking分享应用内图片
Convert yv12 to rgb565 image conversion, with YUV to RGB test
C#中索引器
618再次霸榜的秘密何在?耐克最新财报给出答案
axis设备的rtsp setup头中的url不能带参
How to get the password of cpolar?
2.hacking-lab脚本关[详细writeup]
【TS】1368- 秒懂 TypeScript 泛型工具类型!
Use WinDbg to statically analyze dump files (summary of practical experience)
Filtering of PCL
记录 AttributeError: ‘NoneType‘ object has no attribute ‘nextcall‘
13.信号量临界区保护
14. Code implementation of semaphore
【AGC】如何解决事件分析数据本地和AGC面板中显示不一致的问题?
[visual studio] visual studio 2019 community version cmake development environment installation (download | install relevant components | create compilation execution project | error handling)
UWA report uses tips. Did you get it? (the fourth bullet)