Write a recursive function to insert an element, passed as a parameter, into a binary tree. If the root is empty, the new entry should be inserted into the root, otherwise it should be inserted into the shorter of the two subtrees of the root (or into the left subtree if both subtrees have the same height).
Difficulty level
This exercise is mostly suitable for students
int height(Btree B)
{
if(!B) return 0;
return 1 + max(height(B->left), height(B->right));
}
int insert_BT_rec(BST *B , element e)
{
if(!*B)
{
*B=(BST) malloc(sizeof(struct node));
if(!*B) return 0;
(*B)->data=e;
(*B)->left = (*B)->right=NULL;
return 1;
}
else
if(e==(*B)->data)
return 0;
else
if(height((*B)->left) <= height((*B)->right) )
return insert_BT_rec(&((*B)->left),e);
else
return insert_BT_rec(&((*B)->right),e);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Spelling checker