Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct BSTNode{
- int value;
- struct BSTNode *left;
- struct BSTNode *right;
- }BSTNode;
- BSTNode* InsertNode(BSTNode **root, int x){
- if (!*root){
- *root=malloc(sizeof(BSTNode));
- (*root)->value=x;
- (*root)->left=NULL;
- (*root)->right=NULL;
- return (*root);
- }
- if (x<=(*root)->value)
- (*root)->left= InsertNode(&((*root)->left), x);
- else
- (*root)->right= InsertNode(&((*root)->right),x);
- return (*root);
- }
- void Search(BSTNode** root, int x){
- if ((*root)==NULL){
- printf("NO!\n");
- return;
- }
- if ((*root)->value==x)
- printf("YES!\n");
- else if ((*root)->value>x)
- Search(&((*root)->left), x);
- else
- Search(&((*root)->right), x);
- return;
- }
- void BSTDestroy(BSTNode** root)
- {
- if(!*root)
- return;
- BSTDestroy(&((*root)->left));
- BSTDestroy(&((*root)->right));
- free(*root);
- *root = NULL;
- }
- void BSTPreOrderPrint(BSTNode** root)
- {
- if(!*root)
- return;
- printf("%s\n", (*root)->value);
- BSTPreOrderPrint(&((*root)->left));
- BSTPreOrderPrint(&((*root)->right));
- }
- void BSTInOrderPrint(BSTNode** root)
- {
- if(!*root)
- return;
- BSTInOrderPrint(&((*root)->left));
- printf("%s\n", (*root)->value);
- BSTInOrderPrint(&((*root)->right));
- }
- void BSTPostOrderPrint(BSTNode** root)
- {
- if(!*root)
- return;
- BSTPostOrderPrint(&((*root)->left));
- BSTPostOrderPrint(&((*root)->right));
- printf("%s\n", (*root)->value);
- }
- int main(void){
- BSTNode *root=NULL;
- int i,x;
- for(i = 0; i < 8; i++)
- {
- scanf("%d", &x);
- InsertNode(&root,x);
- }
- BSTPreOrderPrint(&root);
- BSTDestroy(&root);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement