-
Notifications
You must be signed in to change notification settings - Fork 11
/
Day-133.cpp
53 lines (51 loc) · 1.09 KB
/
Day-133.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
53
/*
struct Node {
int data;
Node *left;
Node *right;
Node(int val) {
data = val;
left = right = NULL;
}
};
*/
class Solution{
Node*temp;
bool found = false;
bool next=false;
void dfs(Node* root ,Node *x) {
if (root==nullptr) return;
if (found) {
return ;
}
if (root->data == x->data) {
next = true;
dfs(root->right, x);
return;
}
if (root->left == nullptr && root->right==nullptr) {
if (next) {
temp = root;
next = false;
found = true;
}
return ;
}
dfs(root->left , x);
if (next) {
temp = root;
next = false;
found = true;
}
dfs(root->right , x);
}
public:
// returns the inorder successor of the Node x in BST (rooted at 'root')
Node * inOrderSuccessor(Node *root, Node *x) {
dfs(root ,x);
if (next) {
temp = nullptr;
}
return temp;
}
};