I tried to create a binary search tree by using the insert function.
The the result was not what I expected, it only yielded the first
value of the node of the tree. Can anyone find out what is the problem?
Thank you!
And can someone check if my other functions are right too?
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
struct node* left;
struct node* right;
int val;
}treeNode;
int searchTree(treeNode *T, int key, treeNode *T1, treeNode** p)
{
if(!T)
{
*p=T1;
return 0;
}
else if(T->val==key)
{
*p=T;
return 1;
}
else if(T->val<key)
{
searchTree(T->right,key,T,p);
}
else
{
searchTree(T->left,key,T,p);
}
return 1;
}
int insert(treeNode **T, int key)
{
treeNode *p;
treeNode *s;
if(!searchTree(*T,key,NULL,&p))
{
s= malloc(sizeof(treeNode));
s->val=key;
s->left=s->right=NULL;
if(!p)
{
*T=s;
}
else if(p->val<key)
{
p->right=s;
}
else
{
p->left=s;
}
}
else
{
return -1;
}
return 1;
}
int delete(treeNode **T)
{
treeNode *q;
if(!(*T)->left)
{
q=*T;
*T=(*T)->right;
free(q);
}
else if(!(*T)->right)
{
q=*T;
*T=(*T)->left;
free(q);
}
else
{
treeNode *s;
q=*T;
s=(*T)->right;
while(s->left)
{
q=s;
s=s->left;
}
(*T)->val=s->val;
if(q!=*T) q->left=s->right;
else q->right=s->right;
free(s);
}
return 1;
}
void preOrder(treeNode *T)
{
if(!T) return;
preOrder(T->left);
printf("%d\n",T->val);
preOrder(T->right);
}
int main() {
int a[10]={62,88,58,47,35,73,51,99,37,93};
treeNode *T=NULL;
for(int i=0;i<10;i++)
{
insert(&T,a[i]);
}
preOrder(T);
return 0;
}
The result is 62 rather than the whole array!
searchTreereturns 0 if the tree is empty, otherwise it returns 1. So only only the first call toinsertwill insert a node and return 1, and the other calls toinsertwill return -1. YoursearchTreeshould probably return the result from the recursive call tosearchTree.