-
Notifications
You must be signed in to change notification settings - Fork 0
/
111-bst_insert.c
48 lines (42 loc) · 1.01 KB
/
111-bst_insert.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "binary_trees.h"
/**
* bst_insert - Inserts a value in a Binary Search Tree.
* @tree: A double pointer to the root node of the BST to insert the value.
* @value: The value to store in the node to be inserted.
*
* Return: A pointer to the created node, or NULL on failure.
*/
bst_t *bst_insert(bst_t **tree, int value)
{
bst_t *curr, *new;
if (tree != NULL)
{
curr = *tree;
if (curr == NULL)
{
new = binary_tree_node(curr, value);
if (new == NULL)
return (NULL);
return (*tree = new);
}
if (value < curr->n) /* insert in left subtree */
{
if (curr->left != NULL)
return (bst_insert(&curr->left, value));
new = binary_tree_node(curr, value);
if (new == NULL)
return (NULL);
return (curr->left = new);
}
if (value > curr->n) /* insert in right subtree */
{
if (curr->right != NULL)
return (bst_insert(&curr->right, value));
new = binary_tree_node(curr, value);
if (new == NULL)
return (NULL);
return (curr->right = new);
}
}
return (NULL);
}