-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathig_0406.cpp
More file actions
35 lines (30 loc) · 792 Bytes
/
ig_0406.cpp
File metadata and controls
35 lines (30 loc) · 792 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* @file ig_0406.cpp
* @brief https://leetcode-cn.com/problems/successor-lcci/
* @author YongDu
* @date 2021-09-10
*/
class Solution {
public:
TreeNode *inorderSuccessor(TreeNode *root, TreeNode *node) {
if (nullptr == node || nullptr == root)
return nullptr;
TreeNode *successor = node->right; // 后继节点
if (successor) { // 存在右子树,后继节点为右子树最左节点
while (successor->left) {
successor = successor->left;
}
return successor;
}
// 不存在右子树,在root中找比它大的节点
while (root) {
if (node->val < root->val) {
successor = root;
root = root->left;
} else {
root = root->right;
}
}
return successor;
}
};