Skip to main content

BST (Binary Search Tree)

 




#include <stdio.h>
#include <stdlib.h>
struct treeN
{
    int data;
    struct treeN *left;
    struct treeN *right;
   
};

struct treeN *BSTcreate(struct treeN *root, int val)
{
    if(root == NULL){
        struct treeN *root = malloc(sizeof(struct treeN));
        root->data = val;
        root->left = NULL;
        root->right = NULL;
        return root;
    }
     if (val < root->data)
    {
        root->left = BSTcreate(root->left, val);
    }
    else
    {
        root->right = BSTcreate(root->right, val);
    }
    return root;
}

void inorder(struct treeN *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        printf(" %d ", root->data);
        inorder(root->right);
    }
}
void preorder(struct treeN *root)
{
    if (root != NULL)
    {
        printf(" %d ", root->data);
        preorder(root->left);
        preorder(root->right);
    }
}
void postorder(struct treeN *root)
{
    if (root != NULL)
    {
        postorder(root->left);
        postorder(root->right);
        printf(" %d ", root->data);
    }
}
int main()
{
   
    struct treeN *root = NULL;
    root = BSTcreate(root,43);
    BSTcreate(root,10);
    BSTcreate(root,79);
    BSTcreate(root,90);
    BSTcreate(root,12);
    BSTcreate(root,54);
    BSTcreate(root,11);
    BSTcreate(root,9);
    BSTcreate(root,50);
   
   
 
    inorder(root);
   
    return 0;
}

Comments