-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find inorder successor and inorder predecessor in a BST.cpp
141 lines (132 loc) · 2.9 KB
/
Find inorder successor and inorder predecessor in a 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// { Driver Code Starts
// C++ program to find predecessor and successor in a BST
#include <iostream>
using namespace std;
// BST Node
struct Node
{
int key;
struct Node *left;
struct Node *right;
Node(int x){
key = x;
left = NULL;
right = NULL;
}
};
int key=0;
// This function finds predecessor and successor of key in BST.
// It sets pre and suc as predecessor and successor respectively
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key);
void insert(struct Node *root,int n1,int n2,char lr)
{
if(root==NULL)
return;
if(root->key==n1)
{
switch(lr)
{
case 'L': root->left=new Node(n2);
break;
case 'R': root->right=new Node(n2);
break;
}
}
else
{
insert(root->left,n1,n2,lr);
insert(root->right,n1,n2,lr);
}
}
// Driver program to test above functions
int main()
{
/* Let us construct the tree shown in above diagram */
int t,k;
cin>>t;
while(t--)
{
int n;
cin>>n;
struct Node *root=NULL;
Node *pre=NULL;
Node *suc=NULL;
while(n--)
{
char lr;
int n1,n2;
cin>>n1>>n2;
cin>>lr;
if(root==NULL)
{
root=new Node(n1);
switch(lr){
case 'L': root->left=new Node(n2);
break;
case 'R': root->right=new Node(n2);
break;
}
}
else
{
insert(root,n1,n2,lr);
}
}
// Inorder(root);
//Node * target =ptr;
//printkdistanceNode(root, target, k);
//cout<<endl;
cin>>key;
findPreSuc(root, pre, suc, key);
if (pre != NULL)
cout << pre->key;
else
cout << "-1";
if (suc != NULL)
cout <<" "<<suc->key<<endl;
else
cout << " "<<"-1"<<endl;
}
return 0;
}// } Driver Code Ends
/* BST Node
struct Node
{
int key;
struct Node *left, *right;
};
*/
// This function finds predecessor and successor of key in BST.
// It sets pre and suc as predecessor and successor respectively
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
{
// Your code goes here
if(!root){
return;
}
if(root->key==key){
if(root->left){
Node* temp=root->left;
while(temp->right){
temp=temp->right;
}
pre=temp;
}
if(root->right){
Node* temp=root->right;
while(temp->left){
temp=temp->left;
}
suc=temp;
}
return ;
}
if(root->key > key){
suc=root;
findPreSuc(root->left,pre,suc,key);
}
else{
pre=root;
findPreSuc(root->right,pre,suc,key);
}
}