I made a binary tree but it has some logic problem can some one point
#include<stdio.h>
#include<stdlib.h>
struct node {
struct node *left, *right;
int data, color;
} *root;
int check = 0;
typedef struct node tree;
tree *create_node(int);
void add_tree(tree *, tree *);
void travel_tree(tree *);
int main()
{
int i, j, value;
tree *nv;
printf("enter value \n");
scanf("%d", &value);
nv = create_node(value);
add_tree(nv, root);
travel_tree(root);
}
tree *create_node(int num)
{
tree *temp;
if (check == 0) {
root = (tree *) malloc(sizeof(tree));
root->data = num;
root->left = NULL;
root->right = NULL;
temp=root;
}
if (check != 0) {
temp = (tree *) malloc(sizeof(tree));
temp->data = num;
temp->left = NULL;
temp->right = NULL;
}
check++;
return temp;
}
void add_tree(tree * something, tree * node)
{
tree *ki;
ki=node;
if (check == 0)
return;
if ((something->data < ki->data) && (ki->left)) {
add_tree(something, node->left);
} else if ((something->data < ki->data) && (ki->left == NULL)) {
//node left is to be added at last
ki->left = something;
return;
}
if ((something->data > node->data) && (ki->right)) {
add_tree(something, node->right);
}
if ((something->data > ki->data) && (ki->right == NULL)) {
//right node is to be added
ki->right = something;
return;
}
}
void travel_tree(tree * temp)
{
if (temp->left) {
travel_tree(temp->left);
printf(" %d", temp->data);
return;
}
if (temp) {
travel_tree(temp);
printf(" %d", temp->data);
return;
}
if (temp->right) {
travel_tree(temp->right);
printf(" %d", temp->data);
return;
}
}
My logic is I will create a node in function create_node and return a pointer to the node.
Will pass this pointer which will be in nv and root is initial call on add_tree function
when it is called subsequently I am passing left or right sibling depending upon the data in nv is greater or less than parent node to left or right.