-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path111-bst_insert.c
More file actions
51 lines (49 loc) · 1.04 KB
/
111-bst_insert.c
File metadata and controls
51 lines (49 loc) · 1.04 KB
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
49
50
51
#include "binary_trees.h"
/**
* bst_insert - inserts a value in a Binary Search Tree
* @tree: double pointer to the root node of the BST to insert the value
* @value: value to store in the node to be inserted
*
* Description: If the address stored in tree is NULL, the created node must
* become the root node. If the value is already present in the tree, it must
* be ignored
*
* Return: a pointer to the created node, or NULL on failure
*/
bst_t *bst_insert(bst_t **tree, int value)
{
bst_t *tmp;
if (tree)
{
if (*tree == NULL)
{
*tree = (bst_t *)binary_tree_node(NULL, value);
return (*tree);
}
tmp = *tree;
while (tmp)
{
if (tmp->n == value)
break;
if (tmp->n > value)
{
if (!tmp->left)
{
tmp->left = (bst_t *)binary_tree_node(tmp, value);
return (tmp->left);
}
tmp = tmp->left;
}
else if (tmp->n < value)
{
if (!tmp->right)
{
tmp->right = (bst_t *)binary_tree_node(tmp, value);
return (tmp->right);
}
tmp = tmp->right;
}
}
}
return (NULL);
}