Tuesday, November 13, 2012

Inorder, Preorder and Postorder Successor and Predecessor Functions inC++


#include<iostream>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
struct node* next;
};
struct node* createnode(int x)
{
struct node* new_node=new struct node;
new_node->data=x;
new_node->left=NULL;
new_node->right=NULL;
new_node->next=NULL;
return new_node;
}
void inord_succ(struct node* root,struct node** prev)
{
if(root)
{
inord_succ(root->left,prev);
if(*prev!=NULL)
{
(*prev)->next = root;
*prev = root;
}
else
{
*prev = root;
}
inord_succ(root->right,prev);
}
}
void inord_pred(struct node* root,struct node** prev)
{
if(root)
{
inord_pred(root->left,prev);
root->next=*prev;
*prev=root;
inord_pred(root->right,prev);
}
}
void preord_succ(struct node* root,struct node** prev)
{
if(root)
{
if(*prev!=NULL)
{
(*prev)->next=root;
*prev=root;
}
else
{
*prev=root;
}
preord_succ(root->left,prev);
preord_succ(root->right,prev);
}
}
void preord_pred(struct node* root,struct node** prev)
{
if(root)
{
root->next=*prev;
*prev=root;
preord_pred(root->left,prev);
preord_pred(root->right,prev);
}
}
void postord_succ(struct node* root,struct node** prev)
{
if(root)
{
postord_succ(root->left,prev);
postord_succ(root->right,prev);
if(*prev!=NULL)
{
(*prev)->next=root;
*prev=root;
}
else
{
*prev=root;
}
}
}
void postord_pred(struct node* root,struct node** prev)
{
if(root)
{
postord_pred(root->left,prev);
postord_pred(root->right,prev);
root->next=*prev;
*prev=root;
}
}
void inorder(struct node* root)
{
if(root)
{
inorder(root->left);
cout<<root->data<<" ";
if(root->next)
{
cout<<root->next->data<<endl;
}
else
{
cout<<endl;
}
inorder(root->right);
}
}
void preorder(struct node* root)
{
if(root)
{
cout<<root->data<<" ";
if(root->next)
{
cout<<root->next->data<<endl;
}
else
{
cout<<endl;
}
preorder(root->left);
preorder(root->right);
}
}
void postorder(struct node* root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
if(root->next)
{
cout<<root->next->data<<endl;
}
else
{
cout<<endl;
}
}
}
int main()
{
struct node* root=createnode(1);
root->left=createnode(2);
root->right=createnode(3);
root->left->right=createnode(4);
root->left->left=createnode(5);
root->right->right=createnode(6);
root->right->left=createnode(7);
root->right->right->left=createnode(8);
//root->right->right->left->left=createnode(10);
root->right->right->right=createnode(10);
struct node* ptr = NULL;
//inord_succ(root,&ptr);
//inord_pred(root,&ptr);
//inorder(root);
//preord_succ(root,&ptr);
//preord_pred(root,&ptr);
//preorder(root);
//postord_succ(root,&ptr);
postord_pred(root,&ptr);
postorder(root);
cout<<endl;
}

No comments:

Post a Comment