Your SlideShare is downloading. ×
  • Like
Inorder successor and predecessor in a binary search tree
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Inorder successor and predecessor in a binary search tree

  • 1,798 views
Published

 

Published in Business , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,798
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
11
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

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