I am trying to write a function that inserts a value into a binary tree. I got this so far:
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
// Insert
struct node* insert (struct node* node, int data)
{
if (node == NULL)
node->data=data;
else
{
if (data < node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right ,data);
}
node->left = NULL;
node->right = NULL;
return node;
}
But everytime I ran it, it stops working. Therefore I think there must be something wrong with my insert function. Any ideas?
There are two problems as far as I can tell:
struct node* insert (struct node* node, int data)
{
if (node == NULL)
node->data=data; // 1: Dereferencing a null pointer is a bad idea.
else
{
if (data < node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right ,data);
}
// 2: Throwing away the subtrees is also a bad idea.
node->left = NULL;
node->right = NULL;
return node;
}
You should use newNode
to create a node in the tree, and keep the subtrees:
struct node* insert (struct node* node, int data)
{
if (node == NULL)
node = newNode(data);
else
{
if (data < node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right ,data);
}
return node;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.