当前位置:网站首页>二叉树专题--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】如何解决事件分析数据本地和AGC面板中显示不一致的问题?

VSCode工具使用

Operator-1 first acquaintance with operator

shell编程01_Shell基础

13. Semaphore critical zone protection

华为游戏初始化init失败,返回错误码907135000

MongoDB 学习整理(条件操作符,$type 操作符,limit()方法,skip() 方法 和 sort() 方法)

Overview of integrated learning

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

Common methods of JS array
随机推荐
Read H264 parameters from mediarecord recording
2. Hacking lab script off [detailed writeup]
1287_FreeRTOS中prvTaskIsTaskSuspended()接口实现分析
Retrofit's callback hell is really vulnerable in kotlin synergy mode!
Windows环境MySQL8忘记密码文件解决方案
What are the popular frameworks for swoole in 2022?
In the face of uncertainty, the role of supply chain
"Talking about podcasts" vol.352 the age of children: breaking the inner scroll, what can we do before high school?
Overview of integrated learning
Jsp webshell Free from killing - The Foundation of JSP
Kustomize使用手册
K-d tree and octree of PCL
618 what is the secret of dominating the list again? Nike's latest financial report gives the answer
MYSQL环境配置
PCL之滤波
[TS] 1368 seconds understand typescript generic tool types!
【付费推广】常见问题合集,推荐榜单FAQ
正则及常用公式
首份中国企业敏捷实践白皮书发布| 附完整下载
HDU1228 A + B(map映射)