Inorder successor and predecessor in a binary search tree
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Inorder successor and predecessor in a binary search tree

on

  • 2,112 views

 

Statistics

Views

Total Views
2,112
Views on SlideShare
2,112
Embed Views
0

Actions

Likes
1
Downloads
9
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Inorder successor and predecessor in a binary search tree Document 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;}