-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInorderSuccesor.cpp
More file actions
85 lines (80 loc) · 1.84 KB
/
InorderSuccesor.cpp
File metadata and controls
85 lines (80 loc) · 1.84 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include<bits/stdc++.h>
using namespace std;
struct Node {
char data;
Node*left;
Node*right;
};
Node* root = NULL;
struct Node* insert(struct Node* root, char x) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node*));
temp->data = x;
temp->left = NULL;
temp->right = NULL;
if(root == NULL) {
root = temp;
}
else if(x <= root->data) {
root->left = insert(root->left, x);
} else {
root->right = insert(root->right, x);
}
return root;
}
struct Node* Find(Node*root, int data) {
if(root == NULL) {
return NULL;
}
else if(root->data == data) {
return root;
}
else if(root->data < data) {
return Find(root->right,data);
}
else {
return Find(root->left,data);
}
}
struct Node* FindMin(Node* root)
{
while(root->left != NULL) {
root = root->left;
}
return root;
}
struct Node* GetSuccessor(struct Node* root, int data) {
struct Node* current = Find(root, data);
if(current == NULL) {
return root;
}
if(current->right!= NULL) {
return FindMin(current->right);
} else {
struct Node* successor = NULL;
struct Node* ancestor = root;
while(ancestor!= current) {
if(current->data < ancestor->data) {
successor = ancestor;
ancestor = ancestor->left;
} else {
ancestor = ancestor->right;
}
}
return successor;
}
}
int main() {
root = insert(root,'F');
root = insert(root,'D');
root = insert(root,'J');
root = insert(root,'B');
root = insert(root,'E');
root = insert(root,'A');
root = insert(root,'C');
root = insert(root,'G');
root = insert(root,'K');
root = insert(root,'I');
root = insert(root,'H');
root = GetSuccessor(root,'C');
cout<<root->data<<endl;
}