当前位置:网站首页>二叉树专题--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;
}
};
边栏推荐
猜你喜欢

Hdu1234 door opener and door closer (water question)

Easyexcel, a concise, fast and memory saving excel processing tool

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

Solutions to a series of problems in sqoop job creation

Use WinDbg to statically analyze dump files (summary of practical experience)

华为AppLinking中统一链接的创建和使用

Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer

【快应用】text组件里的文字很多,旁边的div样式会被拉伸如何解决

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

1287_FreeRTOS中prvTaskIsTaskSuspended()接口实现分析
随机推荐
Dialogue Wu Gang: why do I believe in the rise of "big country brands"?
集成学习概览
华为AppLinking中统一链接的创建和使用
12. Process synchronization and semaphore
Oracle 笔记
华为联机对战服务玩家掉线重连案例总结
(五)APA场景搭建之挡位控制设置
2022爱分析· 国央企数字化厂商全景报告
P1055 [noip2008 popularization group] ISBN number
Windows环境MySQL8忘记密码文件解决方案
学习open62541 --- [66] UA_String的生成方法
Operator-1 first acquaintance with operator
PCL Eigen介绍及简单使用
大华设备播放过程中设置播放速度
Open the encrypted SQLite method with sqlcipher
MYSQL环境配置
axis设备的rtsp setup头中的url不能带参
Use of vscode tool
JSP webshell免杀——webshell免杀
Pywin32 opens the specified window