Binary tree program

Binary tree program and user read Input from file.txt using FILE *fp pointer:-

#include<stdio.h>
#include<stdlib.h>

//binary tree program

struct node{
int data;
struct node *left;
struct node *right;
};

//struct node *root;

int check(struct node *node){
int k,p;

if(node==NULL)
return 0;

if(node->right  && node->right->data<node->data)
return -1;

if(node->left  && node->left->data>node->data)
return -1;

k=check(node->left);
p=check(node->right);

if(k==-1 || p==-1)
return -1;
else
return 0;
}


struct node *insert(struct node *node,int x){

if(node==NULL){
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=x;
return newnode;
}
else if (node->data>x){
node->left=insert(node->left,x);
}
else if (node->data<x){
node->right=insert(node->right,x);
}

return node;

}

void print(struct node *node){
if(node==NULL)
return;

print(node->left);
printf("%d  ",node->data);
print(node->right);
}

int main(){

FILE *fp;
fp=fopen("file.txt","r");  //file.txt (62 6 95 8 0 1)

int n,i,x;
struct node *root=NULL;
fscanf(fp,"%d",&n);


for(i=0;i<n;i++){
fscanf(fp,"%d",&x);
root=insert(root,x);

}

print(root);

root->right->right->data=3;

printf("\nthe bst is :\n");

printf("%d",check(root));

return 0;
}
Copyright © C Program | Java | OpenGL Programming | Hadoop at Computaholics