-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinorderSuccessorBST.cpp
More file actions
94 lines (90 loc) · 1.93 KB
/
inorderSuccessorBST.cpp
File metadata and controls
94 lines (90 loc) · 1.93 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
86
87
88
89
90
91
92
93
94
#include<iostream>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
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 if(root->data > data) return find(root->left,data);
}
node *findMin(node *root)
{
if(root==NULL) return NULL;
node *curr=root;
while(curr->left!=NULL)
curr=curr->left;
return curr;
}
node *getsuccessor(node *root,int data)
{
node *curr=find(root,data);
if(curr==NULL)
return NULL;
if(curr->right!=NULL)
return findMin(curr->right);
else
{
node *ancestor=root;
node *successor=NULL;
while(ancestor!=curr)
{
if(ancestor->data > curr->data)
{
successor=ancestor;
ancestor=ancestor->left;
}
else
{
ancestor=ancestor->right;
}
}
return successor;
}
}
void inorder(node *root)
{
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
node *insert(node *root,int data)
{
if(root==NULL)
{
root=new node;
root->left=NULL;
root->right=NULL;
root->data=data;
}
else if(data <= root->data)
root->left=insert(root->left,data);
else
root->right=insert(root->right,data);
return root;
}
int main()
{
node *root=NULL;
root=insert(root,5);
root=insert(root,10);
root = insert(root,3); root = insert(root,4);
root = insert(root,1); root = insert(root,11);
cout<<"Inorder traversal : ";
inorder(root);
cout<<"\n";
node *successor=getsuccessor(root,1);
if(successor==NULL)
cout<<"No successor found\n";
else
cout<<"Successor is : "<<successor->data<<"\n";
return 0;
}