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

js数组常用方法

2022-06-17

【TS】1368- 秒懂 TypeScript 泛型工具类型!
![2.hacking-lab脚本关[详细writeup]](/img/f3/29745761cd5ad4df84c78ac904ea51.png)
2.hacking-lab脚本关[详细writeup]

LeetCode+ 76 - 80 暴搜专题

【AppLinking实战案例】通过AppLinking分享应用内图片

"Matching" is true love, a new attitude for young people to make friends

MySQL environment configuration

Hdu1228 a + B (map mapping)
![[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)
随机推荐
Disassembling Meitu SaaS: driving the plane to change the engine
洛谷 P3398 仓鼠找 sugar(树上倍增 lca 判断树中两条路径是否相交 结论)
HDU1228 A + B(map映射)
Common methods of JS array
12. Process synchronization and semaphore
面对不确定性,供应链的作用
如何用list组件实现tabbar标题栏
SPSS做Shapiro-Wilk正态分析
2.hacking-lab脚本关[详细writeup]
Leetcode+ 76 - 80 storm search topic
Record attributeerror: 'nonetype' object has no attribute 'nextcall‘
Use of vscode tool
二叉树专题--AcWing 1589. 构建二叉搜索树
Shell programming 01_ Shell foundation
From Read and save in bag file Jpg pictures and PCD point cloud
In the face of uncertainty, the role of supply chain
记录 AttributeError: ‘NoneType‘ object has no attribute ‘nextcall‘
JS settimeout() and interview questions
二叉树专题--AcWing 19. 二叉树的下一个节点(找树中节点的后继)
MYSQL关键字