-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path285-inorder-successor-in-bst.cpp
52 lines (48 loc) · 1.31 KB
/
285-inorder-successor-in-bst.cpp
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// class Solution {
// TreeNode* cache = NULL;
// TreeNode* res = NULL;
// public:
// TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
// if (!root) return NULL;
// if (p->right) {
// auto item = p->right;
// while (item->left) item = item->left;
// return item;
// }
// traverse(root, p);
// return res;
// }
// void traverse(TreeNode* root, TreeNode* p) {
// if (!root) return;
// traverse(root->left, p);
// if (cache == p && !res) {
// cout<<root->val<<endl;
// res = root; return; }
// cache = root;
// traverse(root->right, p);
// }
// };
class Solution {
TreeNode* cache = NULL;
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if (p->right) {
p = p->right;
while (p->left) p = p->left;
return p;
}
TreeNode* candidate = NULL;
while (root != p)
root = p->val > root->val ? root->right : (candidate = root)->left;
return candidate;
}
};