-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path111-bst_insert.c
More file actions
42 lines (39 loc) · 780 Bytes
/
111-bst_insert.c
File metadata and controls
42 lines (39 loc) · 780 Bytes
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
#include "binary_trees.h"
/**
* bst_insert - Inserts a value into a Binary Search Tree (BST).
* @tree: A pointer to a pointer to the root node of the BST.
* @value: The value to insert into the BST.
*
* Return: A pointer to the newly inserted node, or NULL on failure.
*/
bst_t *bst_insert(bst_t **tree, int value)
{
if (*tree == NULL)
{
*tree = binary_tree_node(NULL, value);
return (*tree);
}
else
{
bst_t *tmp = *tree;
bst_t *parent = NULL;
while (tmp != NULL)
{
parent = tmp;
if (value <= tmp->n)
tmp = tmp->left;
else
tmp = tmp->right;
}
if (value <= parent->n)
{
parent->left = binary_tree_node(parent, value);
return (parent->left);
}
else
{
parent->right = binary_tree_node(parent, value);
return (parent->right);
}
}
}