Upcoming SlideShare
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Standard text messaging rates apply

# Inorder successor and predecessor in a binary search tree

1,989

Published on

1 Like
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total Views
1,989
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
12
0
Likes
1
Embeds 0
No embeds

No notes for slide

### Transcript

• 1. Inorder Successor and Predecessor in a binary search tree#include &lt;stdio.h&gt;#include &lt;stdlib.h&gt;typedef struct Node{ struct Node *left, *right; int data;}Node;typedef Node * Tree;Node * predecessor(Tree t, int el){ Node *prev = NULL; while(t){ if(t-&gt;data &lt; el){ prev = t;
• 2. t = t-&gt;right; }else if(t-&gt;data == el){ if(t-&gt;left){ prev = t-&gt;left; if(prev) { while(prev-&gt;right) prev = prev-&gt;right; } } return prev; }else { t = t-&gt;left; } } return NULL; //not in the tree}
• 3. Node * successor(Tree t, int el){ Node *next = NULL; while(t){ if(t-&gt;data &gt; el){ next = t; t = t-&gt;left; }else if(t-&gt;data == el){ if(t-&gt;right){ next = t-&gt;right; if(next){ while(next-&gt;left) next = next-&gt;left; } } return next; }else {
• 4. t = t-&gt;right; } } return NULL; //not in the tree}void insert(Tree t, int el){ if(el &lt;= t-&gt;data) { if(t-&gt;left) insert(t-&gt;left, el); else { t-&gt;left = (Node *)calloc(sizeof(Node), 1); t-&gt;left-&gt;data = el; } } else { if(t-&gt;right) insert(t-&gt;right, el); else { t-&gt;right = (Node *)calloc(sizeof(Node), 1); t-&gt;right-&gt;data = el;
• 5. } }}int main(){ int n; scanf("%d", &amp;n); int a[n]; int i; for(i = 0; i &lt; n; ++i){ scanf("%d", a + i); } Tree t = (Node *)calloc(sizeof(Node), 1); t-&gt;data = a[0]; for(i = 1; i &lt; n; ++i){
• 6. insert(t, a[i]);}int p;scanf("%d", &amp;p);Node * v = predecessor(t, p);if(v){ printf("Predecessor: %dn", v-&gt;data);}else{ printf("No Predecessorn");}v = successor(t, p);if(v){ printf("Successor: %dn", v-&gt;data);}else { printf("No Successorn");
• 7. } return 0;}