Vous êtes sur la page 1sur 3

#include<stdio.

h>
#include<stdlib.h>

typedef struct tree{


int itemValue;
struct tree *leftChild;
struct tree *rightChild;
}TREE;

typedef TREE* TREEPTR;

TREEPTR MakeBST(TREEPTR _bsttree)


{
int n;
printf("Enter value to be inserted\t");
scanf("%d",&n);
if(n == -1)
return _bsttree;
if(_bsttree == NULL)
{
_bsttree = (TREEPTR)malloc(sizeof(TREE));
_bsttree->itemValue = n;
_bsttree->leftChild = NULL;
_bsttree->rightChild = NULL;
return MakeBST(_bsttree);
}
else
{
TREEPTR curr = (TREEPTR)malloc(sizeof(TREE));
TREEPTR next = (TREEPTR)malloc(sizeof(TREE));
next = _bsttree;
while(next != NULL)
{
curr = next;
if(n > next->itemValue)
next = next->rightChild;
else
next = next->leftChild;
}
next->itemValue = n;
next->leftChild = NULL;
next->rightChild = NULL;

if(n > curr->itemValue)


curr->rightChild = next;
else
curr->rightChild = next;

return MakeBST(_bsttree);
}

TREEPTR InsertTree(TREEPTR _tree)


{
int n;
char ch = 'y';
char pos[20];
printf("Enter value to be entered\t");
scanf("%d",&n);
if(n == -1)
return _tree;
printf("Enter position\t");
scanf("%s",pos);
if(n != -1)
{
if(_tree == NULL)
{
_tree = (TREEPTR)malloc(sizeof(TREE));
_tree->itemValue = n;
_tree->leftChild = NULL;
_tree->rightChild = NULL;
return InsertTree(_tree);
}
else
{
int top_pos = 0;
TREEPTR curr = (TREEPTR)malloc(sizeof(TREE));
TREEPTR next = (TREEPTR)malloc(sizeof(TREE));
next = _tree;
while((pos[top_pos]!='\0')&&(next!=NULL))
{
curr = next;
if(pos[top_pos]=='l')
next = next->leftChild;
else if(pos[top_pos]=='r')
next = next->rightChild;
top_pos++;
}
if((pos[top_pos]!='\0'))
{
printf("Not Successful\n");
return InsertTree(_tree);
}
else if(next!=NULL)
{
printf("Not a valid insertion\n");
return InsertTree(_tree);
}
else
{
next = (TREEPTR)malloc(sizeof(TREE));
next->itemValue = n;
next->leftChild = NULL;
next->rightChild = NULL;
if(pos[top_pos - 1] == 'l')
curr->leftChild = next;
else
curr->rightChild = next;
return InsertTree(_tree);
}
}
}

void PreOrder(TREEPTR _tree)


{
if(_tree == NULL)
return;
printf(" %d ", _tree->itemValue);
PreOrder(_tree->leftChild);
PreOrder(_tree->rightChild);
}

void main()
{
TREEPTR _tree = (TREEPTR)malloc(sizeof(TREE));
TREEPTR _bsttree = (TREEPTR)malloc(sizeof(TREE));
_tree = NULL;
printf("Make tree\n");
_tree = InsertTree(_tree);
printf("PreOrder Traversal\n");
PreOrder(_tree);
printf("\n Make BST\n");
_bsttree = MakeBST(_bsttree);
printf("PostOrder Traversal BST\n");
PreOrder(_bsttree);
}

Vous aimerez peut-être aussi