-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_STOII_0053_inorderSuccessor.cc
60 lines (57 loc) · 1.13 KB
/
Problem_STOII_0053_inorderSuccessor.cc
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// seem as leetcode 0285
// https://leetcode-cn.com/problems/inorder-successor-in-bst/
// see at Problem_0285_inorderSuccessor.cc
//
// Morris遍历
class Solution
{
public:
TreeNode *inorderSuccessor(TreeNode *root, TreeNode *p)
{
TreeNode *cur = root;
TreeNode *pre = nullptr;
TreeNode *ans = nullptr;
TreeNode *mostRight = nullptr;
while (cur != nullptr)
{
mostRight = cur->left;
if (mostRight)
{
while (mostRight->right != nullptr && mostRight->right != cur)
{
mostRight = mostRight->right;
}
if (mostRight->right == nullptr)
{
mostRight->right = cur;
cur = cur->left;
continue;
}
else
{
mostRight->right = nullptr;
}
}
if (ans == nullptr && pre == p)
{
ans = cur;
}
else
{
pre = cur;
}
cur = cur->right;
}
return ans;
}
};