-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathinorder pre and succ.c
83 lines (71 loc) · 1.54 KB
/
inorder pre and succ.c
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
// CPP code for inorder successor
// and predecessor of tree
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Node
{
int data;
Node* left,*right;
};
// Function to return data
Node* getnode(int info)
{
Node* p = (Node*)malloc(sizeof(Node));
p->data = info;
p->right = NULL;
p->left = NULL;
return p;
}
/*
since inorder traversal results in
ascending order visit to node , we
can store the values of the largest
no which is smaller than a (predecessor)
and smallest no which is large than
a (successor) using inorder traversal
*/
void find_p_s(Node* root,int a,
Node** p, Node** q)
{
// If root is null return
if(!root)
return ;
// traverse the left subtree
find_p_s(root->left, a, p, q);
// root data is greater than a
if(root&&root->data > a)
{
// q stores the node whose data is greater
// than a and is smaller than the previously
// stored data in *q which is successor
if((!*q) || (*q) && (*q)->data > root->data)
*q = root;
}
// if the root data is smaller than
// store it in p which is predecessor
else if(root && root->data < a)
{
*p = root;
}
// traverse the right subtree
find_p_s(root->right, a, p, q);
}
// Driver code
int main()
{
Node* root1 = getnode(50);
root1->left = getnode(20);
root1->right = getnode(60);
root1->left->left = getnode(10);
root1->left->right = getnode(30);
root1->right->left = getnode(55);
root1->right->right = getnode(70);
Node* p = NULL, *q = NULL;
find_p_s(root1, 55, &p, &q);
if(p)
cout << p->data;
if(q)
cout << " " << q->data;
return 0;
}