-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInorderPredecessor.cpp
More file actions
95 lines (93 loc) · 1.96 KB
/
InorderPredecessor.cpp
File metadata and controls
95 lines (93 loc) · 1.96 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
95
#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 *findMax(node *root)
{
if(root==NULL)
return NULL;
node *curr=root;
while(curr->right!=NULL)
curr=curr->right;
return curr;
}
node *getpredecessor(node *root,int data)
{
if(root==NULL)
return NULL;
node *curr=find(root,data);
if(curr==NULL)
return NULL;
if(curr->left!=NULL)
return findMax(curr->left);
else
{
node *pred=NULL;
node *anc=root;
while(anc!=curr)
{
if(anc->data > curr->data)
{
anc=anc->left;
// pred=anc;
}
else
{
pred=anc;
anc=anc->right;
}
}
return pred;
}
}
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->data=data;
root->left=NULL;
root->right=NULL;
}
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 *predecessor=getpredecessor(root,11);
if(predecessor==NULL)
cout<<"No predecessor found\n";
else
cout<<"Predecessor is : "<<predecessor->data<<"\n";
return 0;
}