当前位置:网站首页>Special topic of binary tree -- acwing 19 The next node of the binary tree (find the successor of the node in the tree)
Special topic of binary tree -- acwing 19 The next node of the binary tree (find the successor of the node in the tree)
2022-07-02 10:58:00 【Morgannr】
The question :
Find the successor of a given node in a binary tree .
Time complexity :
( simulation ) O(h)
Ideas :
Just discuss the situation , As shown in the figure below :
- If the current node has a right son , Then the leftmost node in the right subtree is the successor of the current node . such as F The successor is H;
- If the current node has no right son , You need to follow father The domain keeps looking up , The first one to find is its father Left son's node , Of this node father It is the successor of the current node . For example, the current node is D, Then the first satisfaction is its father The node of the left son is C, be C Of father Namely D In the subsequent , namely F yes D In the subsequent .

/**
* 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;
}
};
边栏推荐
猜你喜欢

二叉树专题--AcWing 1497. 树的遍历(利用后、中序遍历,构建二叉树)

【AGC】构建服务3-认证服务示例

LabVIEW为什么浮点数会丢失精度

Shell programming 01_ Shell foundation

二叉树专题--AcWing 19. 二叉树的下一个节点(找树中节点的后继)

集成学习概览
![[visual studio] visual studio 2019 community version cmake development environment installation (download | install relevant components | create compilation execution project | error handling)](/img/9f/4265f1e3927fcf66602f0fc9e7a9d9.jpg)
[visual studio] visual studio 2019 community version cmake development environment installation (download | install relevant components | create compilation execution project | error handling)

The URL in the RTSP setup header of the axis device cannot take a parameter

SPSS做Shapiro-Wilk正态分析

Hdu1236 ranking (structure Sorting)
随机推荐
UVM——Callback
The URL in the RTSP setup header of the axis device cannot take a parameter
(5) Gear control setting of APA scene construction
shell编程01_Shell基础
点云投影图片
PCL Eigen介绍及简单使用
华为AppLinking中统一链接的创建和使用
【付费推广】常见问题合集,推荐榜单FAQ
PCL之K-d树与八叉树
MYSQL关键字
MySQL lethal serial question 3 -- are you familiar with MySQL locks?
Learn open62541 -- [66] UA_ Generation method of string
Is the account above changtou school safe?
JSP webshell free -- the basis of JSP
【AI应用】海康威视iVMS-4200软件安装
洛谷 P3398 仓鼠找 sugar(树上倍增 lca 判断树中两条路径是否相交 结论)
Pywin32 opens the specified window
UWA报告使用小技巧,你get了吗?(第四弹)
618再次霸榜的秘密何在?耐克最新财报给出答案
How to get the password of cpolar?